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

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I still only have the last value of index or i displaying for all buttons.
@Laetis, can you reproduce it in a fiddle so I can better assist you?
I tried but I am not conforable with this tool, nethertheless all the code is ther: jsfiddle.net/Ly5n9jjd
@Laetis, I have corrected my answer with a working fiddle.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.