Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undifined error after switching through images in Javascript

I am trying to create a website with one picture in the middle that changes after a given time. However after running through the loop once, no picture is shown for a short while and my console shows:

The undefinded error

Shortly after, it switches through the images again. But having the image dissapear for a short while is a no go.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My Javascript looks like this:

var allPictures = new Array();
var index = 0;
allPictures[0] = "imgA.jpg";
allPictures[1] = "imgB.jpg";
allPictures[2] = "imgC.jpg";


addEventListener("load",() => {
    setInterval( function() {
        changeImage()
    }, 500);
});


function changeImage() {
    document.getElementById("galleryPicture").src = allPictures[index];
    if (index < allPictures.length) {
        index += 1;
    } else if (index >= allPictures.length) {
        index = 0;
    }
}

My HTML looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="main.css">
    <title>Website</title>
</head>
<body>

<script src="pictureSwapScript.js"></script>

<div class="galleryPicture">
<img id= "galleryPicture" src="imgA.jpg">
</div>
        
    
</body>
</html>

>Solution :

The problem is the condition used to increment index, it will get outside the boundaries of the array.

Replace it with

    if (index >= allPictures.length - 1) {
        index = 0;
    } else {
        index += 1;
    }

There are other minute improvements that can benefit your code, among which the most obvious to me is replacing:

    setInterval( function() {
        changeImage()
    }, 500);

with just

    setInterval(changeImage, 500);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading