I often need to add events to an element inside a JavaScript loop. If you’ve ever done this before, you know that it wont work unless you change the syntax properly, the event will always fire on the last item in the loop. In this article I will show you the simple concept of using a closure around the event to make it work properly.

The proper way to handle this code only involves 2 words, some parenthesis, and some brackets. Personally, I always forget the way it’s supposed to look, so I am forever storing it for reference in this article!

The Wrong Way

Below is an example of code that won’t work. It’s the same code that would get most people to this article in search of help. It doesn’t work because you overwrite the event with each iteration of the loop.

JAVASCRIPTview code
// the WRONG way
for(var i=1; i<10; i++){
 
    someElement.onclick = function(a1,a2){
        myNewFunction(a1,a2); 
    }
 
}

The Right Way

Below is the correct example. It simply creates an anonymous function that can exist on its own and won’t be overwritten. This is a 2 step process. The first step is to wrap return function(){ ... } around your events action. The second step is simply calling the event handler function using parenthesis (). Your original arguments go in between those parenthesis.

Notice how I named my original arguments ‘arg1’ and ‘arg2.’ Our event handler function can call the arguments anything it wants, which I called ‘a1’ and ‘a2.’

JAVASCRIPTview code
for(var i=1; i<10; i++){
 
    someElement.onclick = function(a1,a2){
        return function(){ myNewFunction(a1,a2); }
    }(arg1,arg2);
 
}

This usage of closures will allow your events to fire properly with the correct parameters. If this tip helped you out, leave a comment!