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
ifstatement actually located after the$(document).ready()statement? In this case it will never show the alert, as this code will always be run before the button is actually clicked.var ButtonPressed = 0;