Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign click handlers in for loop

I'm having several div's #mydiv1, #mydiv2, #mydiv3, ... and want to assign click handlers to them:

$(document).ready(function(){   for(var i = 0; i < 20; i++) {     $('#question' + i).click( function(){       alert('you clicked ' + i);     });   } }); 

But instead of showing 'you clicked 3' when click on #mydiv3 (as for every other click) I get 'you clicked 20'. What am I doing wrong?

like image 652
Philip Avatar asked Nov 03 '10 21:11

Philip


People also ask

Can you add event listeners in a for loop?

You actually can attach event listeners in a for loop # As you can see from this example, an event listener is successfully attached to each button, and the console is logged each time one of them is clicked.

Can multiple event handlers be added to a single element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

What is a click event handler?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.


1 Answers

It's a common mistake to create closures in loops in Javascript. You need to have some sort of callback function like this:

function createCallback( i ){   return function(){     alert('you clicked' + i);   } }  $(document).ready(function(){   for(var i = 0; i < 20; i++) {     $('#question' + i).click( createCallback( i ) );   } }); 

Update June 3, 2016: since this question is still getting some traction and ES6 is getting popular as well, I would suggest a modern solution. If you write ES6, you can use the let keyword, which makes the i variable local to the loop instead of global:

for(let i = 0; i < 20; i++) {   $('#question' + i).click( function(){     alert('you clicked ' + i);   }); } 

It's shorter and easier to understand.

like image 154
Harmen Avatar answered Sep 19 '22 18:09

Harmen