Hi, I’ve only just started hacking around with JS, and have created a basic pop-out effect on a menu, where I wanted to make the pop-out stick when the root list element is actually clicked. It all works fine (I know it’s not an ideal solution but I do like to learn through my own experimentation), but I am puzzled by the behaviour of the variable ‘bit’ in the following code:
// called with window.onload
function load_sub_menu(){
var bit=0;
var toggle=document.getElementById("li_2");
toggle.onmouseover=function(){document.getElementById("pop_out_list").style.display="block";}
toggle.onmouseout=function(){document.getElementById("pop_out_list").style.display="none";}
toggle.onclick=function(){
bit=toggle_sub_menu(document.getElementById("li_2"),bit);
}
};
function toggle_sub_menu(toggle,bit){
if(bit){
document.getElementById("pop_out_list").style.display="block";
toggle.onmouseout=function(){document.getElementById("pop_out_list").style.display="block";};
return 0;
}
else{
document.getElementById("pop_out_list").style.display="none";
toggle.onmouseout=function(){document.getElementById("pop_out_list").style.display="none";};
return 1;
}
};
The menu pops out and stays out, or pops back in and stays in, on a onclick to the root element - therefore ‘bit’ is remembering its value between function calls.
At first I thought that a new global variable ‘bit’ must be being created in the onclick anonymous function call, else how can its value be maintained between function calls, but removing the local declaration just breaks the script.
My searches for this have only returned standard global/local/private etc. explanations of variables in JS.
I’m sure this is something pretty basic but I would really appreciate some enlightenment