Yung Lin Ma
Yung Lin Ma

Reputation: 131

How to randomize the slideshow image in HTML

I have the HTML code below and want to randomize the images. How to accomplish it?

Below the code is part of html, and the code is running to show the images in order. I don't know how to ulter the javascripte and want the images can be showed randomly.

Thank you for your concern and hopefully somebody can help. Lawrence

<div class="slideshow-container">

<div class="mySlides fade">
  <img src="http://i.dailymail.co.uk/i/pix/2017/03/01/14/3DD766C300000578-4271496-image-a-39_1488378897470.jpg" style="width:100%">
</div>

<div class="mySlides fade">
  <img src="https://hips.hearstapps.com/roa.h-cdn.co/assets/16/30/1469467513-01-2016-aston-martin-db9-gt.jpg" style="width:100%">
</div>

<div class="mySlides fade">
  <img src="https://article.images.consumerreports.org/prod/content/dam/CRO%20Images%202017/Magazine-Articles/April/Google-Auto-Profile-images-2017/PRF-811" style="width:100%">
</div>

<div class="mySlides fade">
  <img src="http://www.lexus.com/byl2014/pub-share/images/series/lc.png" style="width:100%">
</div>

</div>
<br>


<script>

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none"; 
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1} 
    slides[slideIndex-1].style.display = "block"; 
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>

Upvotes: 0

Views: 2099

Answers (1)

AdamG
AdamG

Reputation: 2630

You can generate a random number to choose a random image:

function showSlides() {
        var i;
        var slides = document.getElementsByClassName("mySlides");
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none"; 
        }
        slideIndex++;
        if (slideIndex> slides.length) {slideIndex = 1} 
        var rand = Math.floor((Math.random() * slides.length));
        slides[rand].style.display = "block"; 
        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }

Upvotes: 1

Related Questions