dcote
dcote

Reputation: 11

Changing boolean value on document click

sorry for this very basic question but it's makes me crazy, I don't understand what is not working on this very simple Jquery code. I just want to change my "abc" boolean from false to true when clicking on my document and launch an alert when "abc" is true (just for exemple).

$(document).ready(function(){    

  var abc = false;

  $(document).click(function(){
   abc = true;
  });

 if (abc == true){
   alert("ALERT"); 
   //do some other things
 }


});

Somebody to help ? Thanks

Upvotes: 1

Views: 1198

Answers (2)

Erazihel
Erazihel

Reputation: 7605

This is caused by JavaScript using an event model. This is your piece of code with detailed explanations:

var abc = false;

$(document).click(function() {
  // Note that this function is attached to the `click` event
  // It will be triggered only when the `click` event is triggered
  // This means that the code inside it is not executed at the moment
  abc = true;
});

// abc is false at the moment so the if statement won't execute
if (abc == true) { 
  alert("ALERT"); 
  //do some other things
}

To fix this, just put the if statement inside the click handler and it will work fine.

$(document).ready(function() {    

  var abc = false;

  $(document).click(function(){
    abc = true;

    if (abc == true){
      alert("ALERT"); 
      //do some other things
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

Your alert won't launch because it is not inside the click handler. It executes only once when document loaded and stays calm. You should move your checking inside click

$(document).click(function(){
   abc = true;
  if (abc == true){
   alert("ALERT"); 
   //do some other things
 }
  });

moreover, for boolean values you can directly write the varaible name inside if condition as if expect a boolean anyway

if (abc == true){

can be shorten to

if (abc){

So, after putting all your pieces together,

$(document).ready(function() {
    var abc = false;

    $(document).click(function() {

        abc = true;

        if (abc) {
            alert("ALERT");
            //do some other things
        }
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions