jQuery Event Handler created in loop

This is a very common issue people encounter.

JavaScript doesn’t have block scope, just function scope. So each function you create in the loop is being created in the same variable environment, and as such they’re all referencing the same i variable.

To scope a variable in a new variable environment, you need to invoke a function that has a variable (or function parameter) that references the value you want to retain.

In the code below, we reference it with the function parameter j.

   // Invoke generate_handler() during the loop. It will return a function that
   //                                          has access to its vars/params. 
function generate_handler( j ) {
    return function(event) { 
        switchBanners(j, true);
    };
}
for(var i = 1; i <= totalBanners; i++){
   $('#slider-' + i).click( generate_handler( i ) );
}

Here we invoked the generate_handler() function, passed in i, and had generate_handler() return a function that references the local variable (named j in the function, though you could name it i as well).

The variable environment of the returned function will exist as long as the function exists, so it will continue to have reference to any variables that existed in the environment when/where it was created.


UPDATE: Added var before i to be sure it is declared properly.

Leave a Comment