Jump to content

For-Loop To Set Up Event Handlers Doesn't Work


CalBear

Recommended Posts

These work: (sorry about the lack of indents, result of copy/paste) //set up event handlers//change background color on element mouseoverfor(i = 0; i < numTop; i++){ for(n = 0; n < numItems; n++){ items[n].onmouseover = function(){ this.style.backgroundColor = "#CCCCCC"; } items[n].onmouseout = function(){ this.style.backgroundColor = "#FFFF00"; } } //change visibility on element mouseover drop.onmouseover = function(){ this.style.visibility = "visible"; } drop.onmouseout = function(){ this.style.visibility = "hidden"; }} And these work: menu[0].onmouseover = function(){ drop[0].style.visibility = "visible"; } menu[1].onmouseover = function(){ drop[1].style.visibility = "visible"; } menu[2].onmouseover = function(){ drop[2].style.visibility = "visible"; } menu[0].onmouseout = function(){ drop[0].style.visibility = "hidden"; } menu[1].onmouseout = function(){ drop[1].style.visibility = "hidden"; } menu[2].onmouseout = function(){ drop[2].style.visibility = "hidden"; } So Why Doesn't this work??? for(i = 0; i < numTop; i++){ menu.onmouseover = function(){ drop.style.visibility = "visible"; } menu.onmouseout = function(){ drop.style.visibility = "hidden"; }}Firebug says drop is undefined

Link to comment
Share on other sites

Because the variable "i" is local to the function. You're going to need a reference that's not local to the function. You could, for example, put the element as a property of the handler:

for(i = 0; i < numTop; i++){  menu[i].element = drop[i];   menu[i].onmouseover = function(){	 this.element.style.visibility = "visible";  }   menu[i].onmouseout = function(){    this.element.style.visibility = "hidden";  }}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...