Variable holds last value when added to event listener
This was a problem I faced when I had to add event listeners to elements created in a loop such that the elements should ‘alert’ the value of var i when they are clicked.
I am aware that finding words to precisely describe this problem is difficult for me, but I will try to explain using a practical example. Ex: I am creating a ordered list with ten list-items such that when any of the list-items receives a click, its alerts its item no. For instance, If you click on 3rd list-item, it alerts ‘3′, similarly, ‘5′ is alerted when you click on list-item 5.
Most common approach would be to code something like below:
function my_func() { var ol=document.createElement("ol"); document.body.appendChild(ol); for(var i=1; i<11; i++) { var li=document.createElement("li"); li.innerHTML="This is a list item"; li.onclick=function(onClick){alert(i);} ol.appendChild(li); } } my_func(); |
If you try this out in your browser, you will find that the value ‘11′ is alerted irrespective of the list-item that was clicked.
Workaround:
The trick is let an attribute of the element hold the value, and using the onClick event to alert the title of the element! Ex:
<li title="2" onclick="alert(this.title)">This is a list item</li> |
The code would then look like:
<script type="text/javascript"> function my_func() { var ol=document.createElement("ol"); document.body.appendChild(ol); for(var i=1; i<11; i++) { var li=document.createElement("li"); li.innerHTML="This is a list item"; li.setAttribute("title",i);//note this li.onclick=function(onClick){alert(this.title);}//note this ol.appendChild(li); } } my_func(); </script> |
Request: Kindly suggest appropriate brief descriptions or ‘tags’ for this entry. Please use the comment system!
Adding multiple event listeners but memorizes last added
This is a great workaround, I have been trying different things like using multiple variables but none of them worked.
Thanks!
Rickvb
19 Aug 08 at 9:48 pm
Isn’t it quite obvious that alert(i) will show the current value of i (which is 11) after the elements are done generating ?
thanks for the info !
T
22 Aug 08 at 8:40 pm
But don’t you expect them to get parsed when we are passing the argument to the alert() function? What may be actually happening is that the event response is registered as to alert the value of i, the browser not knowing that i is dynamic.
Rohan Shenoy
22 Aug 08 at 9:31 pm