Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Global variables

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script type="text/javascript">
var toggle;
toggle=1;
function open(){
jQuery(window).bind("beforeunload", function(){$.post("logout.php");})
$.post("online.php",function(data){
$("#Layer6").html(data);
});
}

function toggle() 
{
$("#Layer4").animate({height:'toggle'});
$("#Layer6").animate({height:'toggle'});

if(toggle==1)
{
$("#toggle").attr('src',"toggle_up.jpg");
toggle=0;
}
else
{
$("#toggle").attr('src',"toggle_down.jpg");
toggle=1; 
}  

}

</script>

Here i have defined toggle as a global variable,and set its value to be 1 initially. When toggle() is executed,the value of toggle should change as its a global variable.Upon execution,the script doesn't seem to work at all(the toggle part).

Kindly help. Thanks !

like image 259
Anant Avatar asked May 27 '26 10:05

Anant


1 Answers

You've named your variable and function the same name ("toggle"). The function definition is overriding your variable declaration (since it comes afterward). Rename your function to something else, e.g. doToggle().

The reason that this conflict occurs is because you can assign function objects to variables in Javascript. Basically, when you call a function, Javascript looks for either a function with that name, or a variable with that name, in case it holds a reference to a function:

var variable = 3;
variable = function() { alert('Function called') };
variable();     // Calls the function, whose reference is stored in 'variable'
like image 154
Cameron Avatar answered May 30 '26 06:05

Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!