0

I am dynamically creating buttons with a on click event the following way:

//add button
for(i=1;i<=narrow+1;i++){
    var btn = document.createElement("BUTTON");
    btn.id="element"+i;
    var t = document.createTextNode("3D View");
    btn.appendChild(t);
    btn.style.position="absolute";
    btn.style.top="520px";
    btn.style.left=100+120*(i-1)+"px";
btn.addEventListener('click', function(){window.alert(i-1+" "+nmol[i-1]);});

The buttons created are fine but the argument in the function of the addEventListener event seems to no increment at all. When printed i stayed to value 1.

Anyone can explain me why?

Thanks

Laetis
  • 1,337
  • 3
  • 16
  • 28

1 Answers1

1

Modify it so that there is an inner closure within the loop

(function(index){
    btn.addEventListener('click', function(){window.alert(index-1+" "+nmol[index-1]);});
 }
)(i);

What was happening is i was global to the loop and by time the click event was fired, i was the last iterated value.

However, when you enclose a function in a parenthesis, you are effectively making a closure which reduces the scope of variables to within the parenthesis.

See it working here

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53