Possible Duplicate:
Event handlers inside a Javascript loop - need a closure?
I want to simply assign onclick events to a series of li
elements within an unordered list. Instead of doing it the messy way by either defining lots of unique IDs and manually adding the events to each li
element I'd like to do it programatically with a for
loop.
html:
<ul id="homeNav">
<li><a title="Back to home page" href="">home</a></li>
<li><a title="Play" href="">play</a></li>
<li><a title="About the site?" href="">about</a></li>
<li><a title="Latest development news and info." href="">dev blog</a></li>
<div class="clear"></div>
</ul>
Javascript:
window.onload = function()
{
var parentList = document.getElementById('homeNav');
var listItems = parentList.getElementsByTagName('li');
var numItems = listItems.length;
for(var i = 0; i < numItems; i++)
{
listItems[i].onmouseover = function()
{
listItems[i].getElementsByTagName('a')[0].style.color = 'blue';
}
listItems[i].onmouseout = function()
{
listItems[i].getElementsByTagName('a')[0].style.color = '#cccccc';
}
}
}
I get the error listItems[i] is undefined
To me it looks like the event is literally looking for the i
index variable instead of using the number assigned to it at the time of the event being added to the trigger, or maybe the i
variable isn't within the closures' scope?