0

So, I have a for loop and an array. in each of the elements in that array are buttons, which I want to all have an onmouseover event.

Note: code is simplified to make my point.

for(i = 0; i < array.length; i++){
    var button = document.createElement("button");
    button.onmouseover = function() {doSomething(i)};
}

where doSomething accepts one parameter, i.

When the cursor does hover over any of the butttons, the argument supplied to doSomething - i, is always the length of array, regardless of which button the cursor is hovering over. Why does this happen, and what can I do to ensure the correct arguments are supplied to the function?

Fitzy
  • 1,871
  • 6
  • 23
  • 40

1 Answers1

0

You are binding to the variable, not its value. I.e. you have successfully created a closure in which all functions utilize the same variable i, not a new variable with the value of i.

What you need to do is lock in that value and one way you can do this is to create a function generator and invoke it with that current value of i. E.g.

for(i = 0; i < array.length; i++){
    var button = document.createElement("button");
    button.onmouseover = function(inner_i) { return function(){doSomething(inner_i)} }(i);
}
Corvus Crypto
  • 2,141
  • 1
  • 13
  • 14
  • So I assume the `(i)` placed after the function definition assigns `i` to `inner_i` in the function declaration? – Fitzy Aug 20 '17 at 02:16