0

Possible Duplicate:
Javascript closure inside loops - simple practical example

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.

I need to get alerts containing the respective list item number.

HTML

<ul>
    <li class='listItem'>listitem1</li>
    <li class='listItem'>listitem2</li>
    <li class='listItem'>listitem3</li>
</ul>

JS

var arr = document.getElementsByClassName('listItem');
for (var i = 0; i < arr.length; i++) {
    arr[i].onmouseover = function() {
        alert(i);
    }
}

http://jsfiddle.net/EHcDp/4/

Thanks in advance!

Community
  • 1
  • 1
user1612686
  • 168
  • 2
  • 10

2 Answers2

3
var arr = document.getElementsByClassName('listItem');
for (var i = 0; i < arr.length; i++) {
    (function(i) {
        arr[i].onmouseover = function() {
            alert(i);
        }
    }(i));
}

Read this duplicate to find out why/how this works.

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
2

You need a closure:

var arr = document.getElementsByClassName('listItem');
for (var i = 0; i < arr.length; i++) {
    arr[i].onmouseover = (function(x) {
        return function() {
            alert(x);
        };
    }(i));
}
awm
  • 6,526
  • 25
  • 24