[thelist] Bit of javascript help

Rick den Haan rick.denhaan at gmail.com
Tue Jan 22 12:42:28 CST 2008


Dan Parry wrote:
> for(var i=0; as[i]; i++) {
> 	if(as[i].className == 'snipHelp') {
> 		var t = as[i].id;
> 		as[i].onmouseover = function () {  xhr.showHelp(t, true); }
> 		as[i].onmouseout = function () { xhr.hideHelp(); }
> 	}
> }

> The function works but if there is more than one link on the page that has
> the class name I'm looking for only the last  ID (var t = as[i].id) is
> applied to every (intended) link

Having experienced this behavior quite frequently, I've come up with my own
theory of why this is happening. Consider your function as doing this:

- Loop through all A tags in the array "as"
- If the class name of the current A tag matches "snipHelp":
--- Create a variable "t", and set its value to the ID of the current A tag,
overwriting it if the variable already exists
--- Create a function that should be fired on mouseover of the current A tag
--- Create a function that should be fired on mouseout of the current A tag
- Rinse and repeat until all A tags have been processed

The key here is the creation and overwriting of the "t" variable.

By the time you get to mousing over the A tag, this for-loop has
(presumably) already run. That means that at the time of your mouseover, the
current value of "t" is the ID of the last found A-tag with the class name
"snipHelp".

The solution is actually quite simple.

The internal scope of the function that is fired on mouseover, registers the
element being moused over as "this", which is good, because that means that
in this case "this" refers to the A-tag.

You want to work with the ID attribute of the A-tag being moused over, so
instead of calling xhr.showHelp(t, true), you can call xhr.showHelp(this.id,
true).

Hope that makes sense :) And please feel free to correct me where I'm wrong,
I plan on creating a tutorial around this subject sometime later this week.


> PS I sent this earlier but it didn't seem to turn up... I hope I haven't
> invaded peoples inboxes twice

No problem. I actually received this version of your message at 5:23 PM,
whereas your original came in at 7:20 PM. Maybe your first message scared
your outgoing mailserver into hiding for a few hours?

Cheers,
Rick.




More information about the thelist mailing list