I make a slider and I have an error. Firstly, it does not work, secondly, one of the buttons does not work. The error "Cannot read property 'style' of undefined" appears:

var slide = document.getElementById('slider_ul'); var slides = slide.getElementsByTagName('li'); var currentSlide = 0; function leftBtn() { slides[currentSlide].style.display = 'none'; currentSlide = (++currentSlide)%slides.length; slides[currentSlide].style.display = 'block'; } function rightBtn() { slides[currentSlide].style.display = 'none'; currentSlide = (--currentSlide)%slides.length; slides[currentSlide].style.display = 'block'; } 

The error occurs exactly on the rightBtn function. Thank!

    1 answer 1

    Why does not it work:

     var a = -1; var b = 3; console.log(a, "%", b, "=", a % b); 

    How to:

     var slide = document.getElementById('slider_ul'); var slides = slide.querySelectorAll('li'); var currentSlide = 0; function leftBtn() { slides[currentSlide].style.display = 'none'; currentSlide = (++currentSlide) % slides.length; slides[currentSlide].style.display = ''; } function rightBtn() { slides[currentSlide].style.display = 'none'; currentSlide = (--currentSlide + slides.length) % slides.length; slides[currentSlide].style.display = ''; } 
     <ul id="slider_ul"> <li>First</li> <li style="display:none">Second</li> <li style="display:none">Third</li> </ul> <button type="button" onclick="rightBtn()">Previous</button> <button type="button" onclick="leftBtn()">Next</button> 

    • Unfortunately not working. - Malyuga
    • @Malyuga Works. You copied my code incorrectly. - Igor
    • The error disappeared, but the slider still does not work. Buttons are simply pressed - Malyuga
    • @Malyuga Click the "Run code" button in the second snippet. Do you understand what is happening? - Igor
    • Fulfilled, yes, I understand the logic of this - Malyuga