Home > Net >  My variable in javascript is not staying true after being called in an onclick function
My variable in javascript is not staying true after being called in an onclick function

Time:09-01

I have a variable that I want to start off as false, and after an .onclick function, I want it to be toggled to true.

This is my Javascript, any help is appreciated.

The "start" variable is the one I am having trouble with, everything else shown works fine, but if there's any helpful hints related to any of it, feel free to mention them.

const left_button = document.getElementById("left")
const right_button = document.getElementById("right")
const start_game = document.getElementById("start-game");
const start_game_button = document.getElementById("");
const player_1_name = document.getElementById("player1");
const player_2_name = document.getElementById("player2");
const score1 = document.getElementById("score1");
const score2 = document.getElementById("score2");
var start = false;

score1.style.display = "none";
score2.style.display = "none";

start_game.onclick = function(){
    player_1_name.innerHTML = prompt("Name of Player One: ");
    player_2_name.innerHTML = prompt("Name of Player Two: ");
    start_game.style.display = "none";
    score1.style.display = "";
    score2.style.display = "";
    var start = true;
}

if (start == true) {
    left_button.onclick = function(){
        alert("test");
    }
}

CodePudding user response:

Don't do var start = true;

This is effectively reassigning another variable named "start".

Just do start = true;

CodePudding user response:

You define start equal to false:

var start = false;

Then you create a function which won't be called until some later time. Then immediately check the value of start:

if (start == true) {
  left_button.onclick = function(){
    alert("test");
  }
}

start was just defined as false, so this if block won't execute.

Basically, you're thinking of it backwards. You're trying to do this:

If the value is true, define a click handler

Instead, do this:

Define a click handler, and within the click handler check if the value is true

For example:

left_button.onclick = function(){
  if (start == true) {
    alert("test");
  }
}

Aside from that, the other answer posted also points out that you're shadowing the start variable here:

start_game.onclick = function(){
  //...
  var start = true;
}

Basically this declares an entirely new variable that only exists within the scope of that function and then is never used. Don't re-declare a new variable, just assign a value to the variable you already have:

start_game.onclick = function(){
  //...
  start = true;
}
  • Related