Links

Lists

Latest Updates

Ruby On Rails List
Python list
Advanced Java
The JavaScript List
Apache Users
Full Disclosure
Linux Security

Search the archives!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Javascript] A loop this this script?


  • From: and-babble at doxdesk.com (Andrew Clover)
  • Subject: [Javascript] A loop this this script?
  • Date: Wed Jun 22 14:35:04 2005

Matt Warden <mwarden@xxxxxxxxx> wrote:

> for (var i=0; i<navBar.length; i++) {
>   navBar[i].onmouseover=function() {
>     document.getElementById(ids[i]).style.visibility="visible";
>   }; [...]
> }

This won't work because JavaScript is a late-evaluating language. That 
is, it evaluates the 'i' in the anonymous function getElementById call 
when it is used, *not* when the function is assigned. That is, *after* 
the loop, not *in* the loop. So when the onmouseover function eventually 
gets called, 'i' is equal to the value it had after the loop exited - 
namely navBar.length.

There are lots of potential workarounds. Personally I'd try to cut down 
on the anonymous functions, and hide the extra information in a property 
on the page element (which its event handler will always have access to 
as 'this'):

   function hover_mouseover() {
     document.getElementById(this.hover_id).style.visibility= 'visible';
   }
   [...]

   for (var i= navBar.length; i-->0;) {
     navBar[i].hover_id= ids[i];
     navBar[i].onmouseover= hover_mouseover;
     navBar[i].onmouseout= hover_mouseout;
   }

-- 
Andrew Clover
mailto:and@xxxxxxxxxxx
http://www.doxdesk.com/