4

I wrote simple code to show/hide some layers after clicking buttons (5 in total) and to change color of the clicked buttons. That works fine. But then I wanted to show a certain element - an arrow - only after clicking first button using a boolean variable and it's not working, the if statement never returns first (hooray) part. What am I missing?

var click01 = false;

function allowright1() {
  if (click01 == true) {
    console.log('hoooray');
    $('#right_arrow').removeClass('hidden').addClass('visible');
  } else {
    console.log('not working');
  }
};

$('#tile1_p1').click(function() {
  if ($('#1layers1').css('display') == 'none') {
    $('#1layers2, #1layers3, #1layers4, #1layers5').removeClass('block').addClass('none');
      $('#tile2_p1, #tile3_p1, #tile4_p1, #tile5_p1').removeClass('orange');
      $('#1layers1').removeClass('none').addClass('block'); $('#tile1_p1').removeClass('white').addClass('orange');
      var click01 = true; 
      console.log('click01 ' + click01); 
      allowright1();
    }
    else if ($('#1layers1').css('display') == 'block') {
      $('#1layers1').removeClass('block').addClass('none');
      $('#tile1_p1').removeClass('orange').addClass('white');
    }
  });
5
  • 5
    You need to remove var with click01 = true; in the event handlers Commented Dec 7, 2017 at 11:08
  • 1
    With var click01, you are declaring the variable, you are assigning value to the global variable, just removed var keyword and you are done! Commented Dec 7, 2017 at 11:10
  • 1
    have a look at variables scopes and closures w3schools.com/js/js_function_closures.asp Commented Dec 7, 2017 at 11:11
  • 2
    @glutengo Please don't use W3Schools as a reference. Their articles are often outdated and sometimes just plain wrong. MDN is far more comprehensive and accurate: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 7, 2017 at 11:12
  • YES! removing "var" in the event handlers was the solution, many thanks guys :) Commented Dec 7, 2017 at 13:55

1 Answer 1

4

You are not resassigning the top level variable click01.

By specifying var click01 = true; you are declaring a variable inside of your click handler that is different to the top level variable. If you remove the var it should work for you, e.g.

$(...).click(function() {
  ...
  click01 = true; // by removing var we reassign the top level variable
  ...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.