Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code is displaying, without any changes in the image. Could someone kindly point out what I might be doing wrong? Below are the sections of code related to the slideshow:

Javascript:

var imageArray = ["media/Chicken Itza.jpg", "media/Christ the Redeemer.jpg", "media/Colosseum.jpg", "media/Great Wall of China.jpg", "media/Machu Picchu.jpg", "media/Petra.jpg", "media/TajMahal.jpeg"];
var imageIndex = 0; 
var mainImage = document.getElementById('mainImage');
mainImage.src = imageArray[0];

function slideshow() {
    mainImage.innerHTML = imageArray[imageIndex];
    imageIndex = imageIndex++;
    if (imageIndex > imageArray.length - 1) {
        imageIndex = 0;
    }
}

HTML:

<body onload="slideshow()">
<img id="mainImage" class="mainslides animate-fading" src="media/Chicken Itza.jpg">
</body>

Complete HTML code:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author(s)" content="Nathan, Jacob, Tee Kiat">
    <meta name="description" content="FED project by Nathan, Jacob, and Tee Kiat">
    <title>FED assignment (7 wonders of the world)</title>
    <link rel="stylesheet" href="7 wonders.css">
    <script src="index.js"></script>
</head>
<body onload="slideshow()">

    <div id="hmenu" class="hamburger_menu">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">x</a>
        <a href="javascript:void(0)" id="main_gwow">The 7 wonders of the world<br>=====================</a>
        <a href="#" id="gwow1">Great Wall of China</a><br><!--China-->
        <a href="#" id="gwow2">Petra</a><br><!--Jordan-->
        <a href="#" id="gwow3">Christ the Redeemer</a><br><!--Brazil-->
        <a href="#" id="gwow4">Machu Picchu</a><br><!--Peru-->
        <a href="#" id="gwow5">Chicken Itza</a><br><!--Mexico-->
        <a href="#" id="gwow6">Colosseum</a><br><!--Italy-->
        <a href="#" id="gwow7">Taj Mahal</a><!--India-->
    </div>
        <span id="hamspan" style="font-size:30px;cursor:pointer;" onclick="openNav()">&#9776</span>
        <h1 id="title">The 7 wonders of the World</h1><br>

    <section id="generalimg">
        <img id="mainImage" class="mainslides animate-fading" src="media/Chicken Itza.jpg">
    </section>    


</body>
</html>

Javascript:

var imageArray = ["media/Chicken Itza.jpg", "media/Christ the Redeemer.jpg", "media/Colosseum.jpg", "media/Great Wall of China.jpg", "media/Machu Picchu.jpg", "media/Petra.jpg", "media/TajMahal.jpeg"];
var imageIndex = 0;
var mainImage = document.getElementById('mainImage');
mainImage.src = imageArray[0];

function slideshow() {
    mainImage.innerHTML = imageArray[imageIndex];
    imageIndex = imageIndex++;
    if (imageIndex > imageArray.length - 1) {
        imageIndex = 0;
    }
    setTimeout(slideshow, 2000); 
}


function openNav() {
    document.getElementById("hmenu").style.width = "250px";
}

function closeNav() {
    document.getElementById("hmenu").style.width = "0";
}

CSS:

body {
    font-family: "Lato", sans-serif;
}

.mainslides {
   width: 450px;
   height: 500px; 

}
.animate-fading {
         animation: fading 5s infinite;
}

@keyframes fading {
    0% {
        opacity: 0;
    }   

    50% {
        opacity: 1;
    }

    100% {
        opacity: 0;
    }
}
}
figcaption {
    font-style: italic;
}

/*DO NOT TOUCH*/
h1, #hmenu, section {
    text-align: center;
}
.hamburger_menu {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.hamburger_menu a { 
    padding-top: 5px;
    text-decoration: none;
    font-size: 15px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

#gwow1:hover, #gwow2:hover, #gwow3:hover, #gwow4:hover, #gwow5:hover, #gwow6:hover, #gwow7:hover, #main_gwow {
    color: #f1f1f1;
}

.hamburger_menu .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 100px;
}

@media screen and (max-height: 450px) {
    .hamburger_menu {
        padding-top: 15px;
    }

        .hamburger_menu a {
            font-size: 18px;
        }
}

#hamspan {
    float: left;
}

Answer №1

Despite my extensive research across multiple websites, I am still struggling to correctly implement the code. Currently, only the image set in the HTML code is displayed, with no further changes occurring. Can someone please point out where I am making a mistake?

The issue lies in failing to call the slideshow method again!

To ensure the image changes every 2 seconds, add the following line at the end of the method:

setTimeout( slideshow, 2000 ); //this line should be included

Additionally, remember to set the src property of the image instead of its innerHTML

mainImage.src = imageArray[imageIndex]; 

or

mainImage.setAttribute( "src", imageArray[imageIndex] );  

That is,

function slideshow() {
    mainImage.src = imageArray[imageIndex]; //this line has also been modified
    imageIndex = imageIndex++;
    if (imageIndex > imageArray.length - 1) {
        imageIndex = 0;
    }
    setTimeout( slideshow, 2000 ); //this line is added
}

Answer №2

To implement the changes suggested by @guruvinder372, you must also make another crucial modification to fix the carousel. Take a look at the following code snippet.

imageIndex = imageIndex++;

When this function is called, it will always set the value of imageIndex to 0 because the statement above assigns the value first and then increments it. To properly increment the value first and then assign it, you should use the following approach:

imageIndex = ++imageIndex;

DEMO

In the demo provided, you may not see the images, but you can use F12 to verify if the image src is being updated correctly.

JS

var imageArray = ["media/Chicken Itza.jpg", "media/Christ the Redeemer.jpg", "media/Colosseum.jpg", "media/Great Wall of China.jpg", "media/Machu Picchu.jpg", "media/Petra.jpg", "media/TajMahal.jpeg"]
var imageIndex = 0; 
var mainImage = document.getElementById('mainImage');
mainImage.src = imageArray[0];

function slideshow() {
   mainImage.src = imageArray[imageIndex]; //this line is changed as well
   imageIndex = ++imageIndex;
   if (imageIndex > imageArray.length - 1) {
       imageIndex = 0;
   }
   setTimeout( slideshow, 2000 ); //this line is added
}

HTML

<body bgcolor="white" onload="slideshow()">
  <img id="mainImage"class="mainslides animate-fading" src="media/Chicken Itza.jpg" width="200" height="200">
</body>

Answer №3

Give this a shot!

function imageSlideshow() {
  setInterval(function (){
    mainPic.src = picturesArray[picIndex];
    picIndex++;
    if (picIndex > picturesArray.length - 1) {
      picIndex = 0;
    }
  }, 1000);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The flying saucer fails to display images when viewing PDFs

Having some trouble converting HTML to PDF as the images in the HTML are not showing up in the PDF file. pom.xml <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>flying-saucer-core</artifactId> <v ...

Navigating a secure Koa authentication flow using compose mechanism

I have this isAuthenticated function in expressjs that composes middleware into one. Now, I need to achieve the same functionality in Koa as I am migrating from Express. How can I replicate this in Koa? import compose from 'composable-middleware&apos ...

What is the best way to customize the appearance of these two images within a div element?

While working on a small website project during my internship, I initially used an inline stylesheet. However, upon my boss's recommendation, I switched to an external stylesheet. Now, I'm trying to figure out how to style the two images within d ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

Challenges with looping in Jquery animations

I've been working on an animation function that I want to run in a loop. So far, I've managed to get it to work for one iteration, but I'm struggling to figure out how to repeat the loop a specific number of times. Below is the code for my a ...

When hovering, transition occurs unless the cursor is over a specific element

I have created a small box element with a close button that looks like this: ___ | X| ‾‾‾ In order to make it more interactive, I applied some CSS so that when hovered, the box expands like this: ___________________ | X| ‾ ...

A guide to extracting and storing JSON data in JavaScript variables

I have integrated the CheckPoint API into my web application and I need to store the "sid" in a variable for further use. How can I achieve this? Below is the code snippet I am using to log in: var myHeaders = new Headers(); myHeaders.append("Content-Type ...

Tips for conducting performance analysis in React 16

In the React documentation, it is mentioned that react-addons-perf does not function with React 16 and suggests using Chrome's built-in tools for equivalent functionality. However, in my experience, I have not found this to be true. For example, let& ...

Tips for selecting a dropdown item that shares the same data-testid

I am attempting to use Selenium to click on an option in a dropdown menu. The options all have the same 'data-testid', and the only unique identifier appears to be the link text. Does anyone know of a way to select a specific choice within the dr ...

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

Load a 3D object or model using three.js and then make modifications to its individual components

Seeking advice on displaying and manipulating a 3D model of a robot arm in a browser. How can I load the model into three.js to manipulate all the sub-parts of the robot arm? Using Inventor, I have an assembly of a rotary motor and a shaft exported as an ...

What are some ways to remove scroll bars from an iframe?

I'm having trouble with scroll bars appearing in my iframe when inside a fancy box. I have tried everything to remove them without success. For example, you can view the issue here: http://jsfiddle.net/t4j3C/ No matter what I try, nothing seems to w ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

Ways to delete a document from Mongodb depends on the existence of a more recent document

Is there a way to automatically delete previous database insertions in my meteor web app whenever a new document is inserted? I've attempted the following code, but it hasn't been successful: if(SearchLobby.find({profile: Meteor.userId()}).count ...

How to prioritize indices when querying multiple indexes in Elasticsearch?

Utilizing the Elasticsearch multi index API, I am able to query across multiple indices. However, it is important for me to prioritize my queries. As an illustration, when querying in the indices index1 and index2, the syntax would look like: /index1,ind ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

Strange actions observed in AJAX POST request

This code snippet functions perfectly when I set a breakpoint in the backend and allow the value to be zero before continuing with the rest of the code. However, if I don't set a breakpoint and let it run, the value will become 2 and cause a break in ...

The collaboration of Node.js and React.js on a single server

Separate ports are used for Node and React, but API requests from the React app can be proxied to the Node URL. I have opted not to implement server-side rendering for React in order to serve the React app. Instead, I build the React app each time there i ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...