3

i have a little problem with passing the index to eventlistener in for loop.

for (var i = 0; i < todos.length; i++) {
    console.log("XD");
    todos[i].addEventListener("mouseover", function() {
        trashShow[i].style.display = "inline";
    });
}

Communicate shows up that say "Cannot read property 'style' of undefined". I think that the index is just wrong so there is not this element in the array. Thanks for help.

Trebuh
  • 43
  • 5
  • Possible duplicate of [Variable out of scope when applying event listener](https://stackoverflow.com/questions/19203992/variable-out-of-scope-when-applying-event-listener) – Maxime Chéramy May 13 '18 at 10:48
  • https://stackoverflow.com/questions/20587714/addeventlistener-for-index-how-to-use-closure – Maxime Chéramy May 13 '18 at 10:50

1 Answers1

3

i have a little problem with passing the index to eventlistener in for loop.

If you declare the iterator variable i with let, rather that with var, you will see that the loop increments i correctly each time within the event listener and never returns an undefined error.

Working Example:

var sections = document.getElementsByTagName('section');

var section1Divs = sections[0].getElementsByTagName('div');
var section2Divs = sections[1].getElementsByTagName('div');

for (let i = 0; i < section1Divs.length; i++) {

    section1Divs[i].addEventListener('mouseover', function() {
        section2Divs[i].style.backgroundColor = 'rgb(255, 0, 0)';
    });

    section1Divs[i].addEventListener('mouseout', function() {
        section2Divs[i].style.backgroundColor = 'rgb(191, 191, 191)';
    });
}
div {
display: inline-block;
width: 50px;
height: 50px;
margin-right: 12px;
background-color: rgb(191, 191, 191);
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>

<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>

Further Reading:

What's the difference between using "let" and "var" to declare a variable in JavaScript?

Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 1
    Thanks. I needed the same help and changed var to let and it worked. I wish the author of this question would vote correct as he was doing the same thing I was doing. Although I was using click, not mouseover. – Jonathan J. Pecany Aug 03 '20 at 17:31
  • Thanks, @JonathanJ.Pecany - when I first started learning javascript (in 2013) it was still ES5 and `let` & `const` didn't exist. Applying `eventListeners` to multiple nodes in a loop was one of the first really difficult things I had to learn. When `let` arrived it made things much easier! – Rounin Aug 03 '20 at 18:10