title: Javascript undefined variable error
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure">Event handlers inside a Javascript loop - need a closure?</a>  </p>
  </blockquote>
  
  
  
  <p>I want to simply assign onclick events to a series of <code>li</code> 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 <code>li</code> element I'd like to do it programatically with a <code>for</code> loop.</p>
  
  <p>html:</p>
  
  <pre><code>&lt;ul id="homeNav"&gt;
      &lt;li&gt;&lt;a title="Back to home page" href=""&gt;home&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a title="Play" href=""&gt;play&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a title="About the site?" href=""&gt;about&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a title="Latest development news and info." href=""&gt;dev blog&lt;/a&gt;&lt;/li&gt;
      &lt;div class="clear"&gt;&lt;/div&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre><code>window.onload = function()
  {
      var parentList = document.getElementById('homeNav');
      var listItems = parentList.getElementsByTagName('li');
      var numItems = listItems.length;
      for(var i = 0; i &lt; 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';
          }
      }
  }
  </code></pre>
  
  <p>I get the error <code>listItems[i] is undefined</code></p>
  
  <p>To me it looks like the event is literally looking for the <code>i</code> index variable instead of using the number assigned to it at the time of the event being added to the trigger, or maybe the <code>i</code> variable isn't within the closures' scope?</p>