Jump to content
Sign in to follow this  
CalBear

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

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

Share this post


Link to post
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";  }}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...