[thelist] Several javascript issues.

Edwin Martin edwin at bitstorm.org
Tue Jul 24 16:02:47 CDT 2007


Jon Hughes wrote:
> The Code:
>
> window.onload = function()
> {
> var popinfo =
> document.getElementById("content").getElementsByTagName("img");
> for (var i=0; i<popinfo.length; i++) {
> 	if (popinfo[i].alt == "Click for more details") {
> 	popinfo[i].onmouseover = function() { var popname =
> popinfo[i].title; alert(popname); }
> popinfo[i].onmouseout = function() { var popname = popinfo[i].title;
> alert(popname); }
> 	}
> }
> }
>
> This doesn't work.  The error in firebug when I mouseover the image is:
> "Popinfo[i] has no properties"
>   

This is because there's only one i variable. At the end i is equal to 
popinfo.length and popinfo[i] doesn't exist.


> Now, if I do this:
>
>
> window.onload = function()
> {
> var popinfo =
> document.getElementById("content").getElementsByTagName("img");
> for (var i=0; i<popinfo.length; i++) {
> 	if (popinfo[i].alt == "Click for more details") {
> var popname = popinfo[i].title;
> 	popinfo[i].onmouseover = function() { alert(popname); }
> popinfo[i].onmouseout = function() { alert(popname); }
> 	}
> }
> }
>
> It doesn't give me any errors when I mouseover, but the alert is for the
> last popinfo[i] in the array, where I want the one currently being
> mouse'd over.
>
> I apologize for not having a test page, I am at work and have no access
> to one.
>   

This is almost the same problem. Only one popname variable which has the 
value of the last image-title.

You entered one of the more advanced topics of JavaScript programming.

There are several solution (none of which is really simple).

1) Use curry (see Wikipedia for an explanation and a JavaScript snippet 
you can use).

2) Use "event handler factories". These are functions which generate 
event handler functions.

3) Wrap the event-handler parts in their own functions.

Here is some example of a event handler factory:

function onMouseOverHandlerGenerator(i) {
	return function() {
		var popname = popinfo[i].title;
		alert(popname);
	};
}

You can then do

popinfo[i].onmouseover = onMouseOverHandlerGenerator(i)


Hope this helps.

Edwin Martin
-- 
http://www.bitstorm.org/edwin/en/



More information about the thelist mailing list