Uncaught TypeError: Cannot read property ‘style’ of undefined for image slider

I’m working on a simple image slider where you click and it moves on to the next image. This is done by changing the z-index of the images on click. For some reason, now that I’ve loaded it into my hosting site, I’m getting the error: “Uncaught TypeError: Cannot read property ‘style’ of undefined” on the Google Chrome console.

The error is specifically happening on the second to last line: “z=images[currentSlide].style.zIndex” Any idea how to fix this?

Here is the relevant HTML and JS:

<section class="fixed-container wrap">

  <div class="logo-bg">
    <div class="slider">
        <img src="https://upload.wikimedia.org/wikipedia/commons/e/e5/Golden_rectangle.png">
        <img src="https://i0.wp.com/mathblog.wpengine.com/wp-content/uploads/2017/03/image005.gif?zoom=2.625&resize=364%2C222&ssl=1">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Rectangle_example.svg/1024px-Rectangle_example.svg.png">
const slideArea = document.querySelector("div.slider")
const images = slideArea.querySelectorAll("img")

<!--we want to keep track of two things-->
let currentSlide = 0
let z = 1

<!--when I click the slide area I want to change the slide based on the z-index-->
wrap.addEventListener('click', function(e){

const width = +getComputedStyle(document.body).width.slice(0, -2) / 2;

if (e.pageX <= width){
    currentSlide = currentSlide - 1
    if(currentSlide < 0){
    currentSlide = images.length
    z= z + 1} 
        currentSlide = currentSlide + 1
        if(currentSlide > images.length - 1){
        currentSlide = 0
        z=z + 1}

<!--remove animation from the style for every image-->
images.forEach(image =>{

images[currentSlide].style.animation="fade .5s"


The problem is likely from currentSlide = images.length.

Indexing starts at zero so images[images.length] will be undefined. The last index is one less than the length.

Try changing to:

currentSlide = images.length - 1;

Leave a Reply

Your email address will not be published. Required fields are marked *