Automatic Image Viewer with JavaScript, HTML, and CSS

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

Good morning, today I’m going to provide you with a tutorial on how to create an automatic image viewer using HTML, CSS, and JavaScript.

Firstly, I will show you the project structure. I use Visual Studio Code as my development environment, and I’ll leave the link for you to download it. But you can use any IDE you prefer.

this is my directory structure

Next, I’ll provide you with the HTML and CSS code required to create it.

<!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="css/style.css">
    <title>Image Viewer - Array Object</title>
    <script>
        var myImageArray = ["assets/cat.jpg","assets/koala.jpg","assets/lion.jpg","assets/dog.jpg"];
        var position = parseInt(0);

        // Set the time interval for the function to execute
        setInterval(nextImage, 1500);

        function nextImage() {
            // If the position is less than the array length, increment by 1 to move to the next image; otherwise, go back to the first image
            if (position <= myImageArray.length-1) {
                position++;
            }
            // Wrap around from the last image to the first
            if (position > myImageArray.length-1) {
                position = 0;
            }
            document.getElementById("photos").src = myImageArray[position];
        }
    </script>
</head>
<body>
    <h1>Image Viewer</h1>
    <div>
        <img src="assets/cat.jpg" id="photos" height="426" width="640"/>
    </div>
</body>
</html>
body {
    text-align: center;
}

In this case, I’ve embedded the script in the HTML, but you can also create an external JavaScript file with the script and then reference it in the HTML.

Leave a Comment