title: JS loop position while iterating through an array
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example">Javascript closure inside loops - simple practical example</a>  </p>
  </blockquote>
  
  
  
  <p>I'd like to output the hover position in the array while iterating through an array of list items. However my logic is totally wrong, since 'i' is always set to the array's lenght by the time the loop has completed, so I always get the array length value instead of the desired position in the array.</p>
  
  <p>I need to get alerts containing the respective list item number.</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;ul&gt;
      &lt;li class='listItem'&gt;listitem1&lt;/li&gt;
      &lt;li class='listItem'&gt;listitem2&lt;/li&gt;
      &lt;li class='listItem'&gt;listitem3&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p><strong>JS</strong></p>
  
  <pre><code>var arr = document.getElementsByClassName('listItem');
  for (var i = 0; i &lt; arr.length; i++) {
      arr[i].onmouseover = function() {
          alert(i);
      }
  }
  </code></pre>
  
  <p><a href="http://jsfiddle.net/EHcDp/4/" rel="nofollow noreferrer">http://jsfiddle.net/EHcDp/4/</a></p>
  
  <p>Thanks in advance!</p>