-2

When I try to run my code I get the error message in the console :

(index):37 Uncaught TypeError: Cannot read property 'addEventListener' of undefined

I saw many post with the same error message for something similar but it didn't helped me

let thumbnails = document.getElementsByClassName('thumbnail')
let activeimages = document.getElementsByClassName('thumbnail-active')

for (var i = 0; i <= thumbnails.length; i++) {
  thumbnails[i].addEventListener('mouseover', function() {
    if (activeimages.length > 0) {
      activeimages[0].classList.remove('thumbnail-active')
    }
    this.classList.add('thumbnail-active')
    document.getElementById('featured').src = this.src
  })
}
<div class="slideshow">
  <div class="displayImage">
    <img id="featured" src="./style/image1.jpg">
  </div>
  <div class="row slide-wrapper">
    <div class="arrow" id="prev"></div>
    <div id="slider">
      <img class="thumbnail thumbnail-active" src="./style/image1.jpg">
      <img class="thumbnail" src="./style/image2.jpg">
      <img class="thumbnail" src="./style/image3.jpg">
      <img class="thumbnail" src="./style/image4.jpg">
      <img class="thumbnail" src="./style/image5.jpg">
    </div>
    <div class="arrow" id="next"></div>
  </div>
</div>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
Jerome
  • 1
  • 1
    `i<=thumbnails.length;` should be `i – epascarello Nov 13 '20 at 20:33
  • 1
    Change `i<=thumbnails.length` to `i – imvain2 Nov 13 '20 at 20:34
  • Probably your query selector didn't find any `thumbnail` class and has no length. In your loop, your condition is `<= thumbnails.length`, which means it tries to access a non-existing item. First, change your condition to `< thumbnails.length`, then check your query selector. – kaveh Nov 13 '20 at 20:34

1 Answers1

-1

Your mistake is in if condition. You are removing class only from first element which has activeimage class. Because of activeimages[0]. Change it to following

 if (activeimages.length >0){
       activeimages[i].classList.remove('thumbnail-active')
   }

Second thing i see is in defining for loop. You should use i<activeimages.length instead of <=

Pinncik
  • 321
  • 3
  • 14