Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have 5 images that I went to appear every few seconds. I wrote this function below but nothing is showing up on my website.

JavaScript
<pre>function imageSlides(){
  let imageArray = ["/imgs/cn1.jpg", "/imgs/cn2.jpg", "/imgs/cn3.jpg", "/imgs/cn4.jpg", "/imgs/cn5.jpg"];

  imageArray.forEach(item => setTimeout(()=> {
    document.getElementById("slide").src = "item";
    
 }, 2000));
 
}


What I have tried:

I have tried using setInterval and calling my function. I'm new to programming so I'm lost right now
Posted
Updated 15-Jul-20 2:37am

1 solution

Unless you have an absolute need to write your own (due to odd display requirements or you are doing it as an exercise) you are going to save a lot of effort simplying getting an open source one off the internet. Bootstrap has one built in, there is a pretty good one called "Slick".

That said, from your code you are setting the src to the literal string "item" rather than the source path held in the variable item, the line should look more like:

JavaScript
document.getElementById("slide").src = item;


The logic also has problem: after you call the function it'll set the source to each image in rapid succession so you'll pretty much just see the end one. It will also only cycle once.

What you need is more like:

JavaScript
function imageSlides(){
  let imageArray = ["/imgs/cn1.jpg", "/imgs/cn2.jpg", "/imgs/cn3.jpg", "/imgs/cn4.jpg", "/imgs/cn5.jpg"];

    var i = 0;
    document.getElementById('silde').src = imageArray[i]; // Inititalise
    setInterval(() =>{
        i += 1;
        if(i === imageArray.length - 1) {
            i = 0; // Show the image at the end of list.
        }
        document.getElementById('silde').src = imageArray[i];
    }, 2000);
   
 }, 2000));
 
}


There are some things you can do to help tidy up the above, but hopefully it is clear enough, also I haven't tested it so there might be off-by-one errors.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900