Dirk Dunn
Dirk Dunn

Reputation: 363

Why won't false become true?

I am working on a game, and for some reason these click functions are not permanently changing the top values to true, I use console log to test it, and the bottom log always says false. I know this might be simple but can anyone let me know?

var twoThree = false;
var fourFive = false;
var sevenEight = false;

// button click functions
$('#2_3').click(function(){
  twoThree = true;
  $('#start').hide();
  $('#game').fadeIn('slow');
});
$('#4_5').click(function(){
  var fourFive = true;
  $('#start').hide();
  $('#game').fadeIn('slow');
});
$('#7_8').click(function(){
  var sevenEight = true;
  $('#start').hide();
  $('#game').fadeIn('slow');
});
console.log(twoThree);

Upvotes: 0

Views: 79

Answers (2)

chfumero
chfumero

Reputation: 1147

The problem is that you are assigning the varibles using the keyword var. This is declaring a new variable on the scope of the function and set it to true. The way to set the variables on the clausure of the functions must be through the window variable o just using the name of the variable.

This two calls will work.

window.fourFive = true;
fourFive = true;

This not.

var fourFive = true; // Is a local variable of the function

Upvotes: 0

chris vdp
chris vdp

Reputation: 2842

Your use of var inside of the functions creates a new variable inside that scope, so the value in the outer scope is not changed.

Upvotes: 3

Related Questions