sakisg27
sakisg27

Reputation: 11

Javascript and JQuery Dom Global Variable Scope

I have problem with scope of the variable in the code

var ButtonPressed; //global SCOPE
$(document).ready(function()
{

  function messageAlert()
  {
    $('#buttons').append('<input type="button" id="btn" value="Clickme" />');
    return false;
  }

  messageAlert();

  $('#btn').on("click", function()
  {
    ButtonPressed = 1;
  });
}); //end document

//// UNDEFINED NOT WORKING
if (ButtonPressed === 1)
{
  alert(ButtonPressed);
}

I try everything about scope tutorials but I can't show variable ButtonPressed=1 GLOBAL.

Any help ?

Upvotes: 0

Views: 75

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18997

Explaining your code. the execution goes this way ( 1 ) --> ( 2 ) --> ( 3 )

    var ButtonPressed; // executed as soon as the script tag is hit -- ( 1 )

    $(document).ready(function()
    {
     //......          //executed ONLY AFTER the DOM is ready - (3 )
    }); 


    if (ButtonPressed === 1) //executed as soon as the script tag is hit - ( 2 )
    { 
      alert(ButtonPressed);
    }

as the comments indicate, the var ButtonPressed is executed first, then the execution skips to the if check . Only after the DOM is completely ready then your code block inside the $(document).ready will execute.

So that means all the global scope code stuff will get executed first and then the one's inside the document ready


1) If your intention is to Show a alert when ever a button is clicked then do this

$('#btn').on("click", function()
  {
    ButtonPressed = 1;
    alert(ButtonPressed);
    // do all the stuff that should happen when a button is clicked
  });

2) Else if your intention is to Check if a button was clicked?? then you can make use of the setInterval. using this you can check if a button was clicked or not for every say 1 secs. Like below.

var checkButtonStatus = setInterval(function(){
                 if (ButtonPressed === 1)
                 { 
                  alert(ButtonPressed);
                  //do all your stuff as the button was clicked
                  clearInterval(checkButtonStatus ); // remove interval as you don't need to check again.
                 }

                }, 1000);

Note: I would say option 2 is not efficient way of doing it, Go for option 1

Upvotes: 0

KAD
KAD

Reputation: 11112

You are binding a click event to the button #btn to set the global variable ButtonPressed which will not be fired unless you click the button.

When your code executes and reaches the block (which is in the global scope) knowing that the button have not been clicked

if (ButtonPressed === 1)
{
  alert(ButtonPressed);
}

The variable ButtonPressed will not be set because you haven't clicked the button so it will not alert any message.

In other words, the if statement runs before the click handler

Upvotes: 2

Related Questions