Airikr
Airikr

Reputation: 6436

Check if button was clicked and return a alert outside the click function

I want to see if a button was clicked. If it was clicked, return a alert outside of the click function. Here's my code:

$(document).ready(function() {
  var test = 0;
  $('body').on('click', '#publish', function() {
    test = 1;
  });

  if(test == 1) {
    alert('jay!');
  }
});

Not it doesn't show the alert window upon click. Why? Do I have to use the if statement inside the click function? I want this code to work as it is.

http://jsfiddle.net/edgren/TXERr/

Thanks in advance.

Upvotes: 1

Views: 4950

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123418

your code can't work because the if statement is executed before the click event. (and as sidenote: as a good practice always use triple equality in your comparison)

Do instead

$(document).ready(function() {
  var test = 0;

  function checkTest() {
    if(test === 1) {
       alert('jay!');
    }
  }

  $('body').on('click', '#publish', function() {
    test = 1;
    checkTest();
  });


});

Upvotes: 5

Related Questions