Since the correct solutions have already been provided ( Andrew Whitaker accepted the answer , which is my favorite), I will actually tell you what the problem is with your code ( yoshi answer has some tips, but does not explain it in detail).
Problem
The problem is that even if the value of i changes in the loop when it is executed, i remains the same (the same as when the for loop ends) when the event handlers are executed.
What really happens in your code
The proof looks like this (see jsfiddle ):
var selectors=['.counter_d','.selector_d','.date_d']; var description=['Counter', 'Selector', 'Date']; for(var i=0; i<selectors.length; i++) $(selectors[i]).mouseover(function() { $('#description').html(i);
Problem - event handlers use i from the outer region, which at run time is equal to 3 by the handler. Therefore, even if the variable i has the value that you want when the handlers are bound, the value changes before they are executed.
Decision
To solve this problem, you can slightly modify your code to use anonymous functions that are immediately called, passing then the correct value of i :
var selectors=['.counter_d','.selector_d','.date_d']; var description=['Counter', 'Selector', 'Date']; for(var i=0; i<selectors.length; i++) (function(i){ $(selectors[i]).mouseover(function() {
To prove that it works correctly: http://jsfiddle.net/ZQ6PB/
More details
Closing JavaScript inside loops is a simple practical example ,