Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript addEventListener not working as expected

I am looking into some common Javascript programs. The following one adds 4 buttons to the DOM and adds an event listener to each of them:

for(var i =0;i<5;i++){
    var btn = document.createElement('button');
    btn.appendChild(document.createTextNode('Button' + i));

    //function 1
    (function(i){
     btn.addEventListener('click', function(){console.log(i)});
     })(i);

    //function 2 commented
    /*btn.addEventListener('click', (function(i){
     return function(){
     console.log(i);
     }
     })(i));*/
    
    document.body.appendChild(btn);
}

both function 1 and function 2 add event listener to the buttons and work perfectly. I want to know, why the following code does not :-

for(var i =0;i<5;i++){
    var btn = document.createElement('button');
    btn.appendChild(document.createTextNode('Button' + i));

    btn.addEventListener('click', function(){
        console.log('Clicked' + i);
    });
    document.body.appendChild(btn);
}

This code just logs 5 for every button on click. Why is that, I do not understand why it simply does not hold the value for i for each loop?

like image 889
Stacy J Avatar asked Jul 17 '26 23:07

Stacy J


1 Answers

Javascript has no block scope if you use var. So, using exactly your code, you can have the "expected result" replacing var for let:

for(let i =0;i<5;i++){
    var btn = document.createElement('button');
    btn.appendChild(document.createTextNode('Button' + i));

    btn.addEventListener('click', function(){
        console.log('Clicked' + i);
    });
    document.body.appendChild(btn);
}
like image 128
Gerardo Furtado Avatar answered Jul 20 '26 14:07

Gerardo Furtado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!