1

I have a image slider code which is working good. But I need to randomise the order of the pics so NOT everytime pic1 is shown first, pic2 shown second and than pic3 shown third. I want to randomise the order of the pics so evertytime page is load, pics to have different order. And I need help with that. Here is my code:

 <img class="mySlides" src="pic1.jpg">
 <img class="mySlides" src="pic2.jpg">
 <img class="mySlides" src="pic3.jpg">


<script>
var myIndex = 0;
carousel();

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

2 Answers2

2

Change the order of elements in-place may help you.

let index = 0;

function randomise_list() {
  const list = document.querySelector("#slider");
  for (let i = list.children.length; i >= 0; i--) {
    list.appendChild(list.children[Math.random() * i | 0]);
  }
}

function run_carousel() {
  const slides = document.querySelectorAll(".slide");
  for (let i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  index++;
  if (index > slides.length) index = 1;
  slides[index - 1].style.display = "block";
  setTimeout(run_carousel, 2000); // Change image every 2 seconds
}

randomise_list();
run_carousel();
<div id="slider">
  <img class="slide" src="https://via.placeholder.com/50x50/333333/cccccc?text=1">
  <img class="slide" src="https://via.placeholder.com/50x50/333333/cccccc?text=2">
  <img class="slide" src="https://via.placeholder.com/50x50/333333/cccccc?text=3">
</div>
0xdw
  • 3,755
  • 2
  • 25
  • 40
  • perhaps you can help with my other question - https://stackoverflow.com/questions/64504802/how-to-randomise-the-order-of-3-divs-showing-consistently-in-10sec-20sec-30sec – santiagoterosa Oct 23 '20 at 17:40
1

Using Math.random() like it is used here:

<img class="mySlides" src="pic1.jpg" />
<img class="mySlides" src="pic2.jpg" />
<img class="mySlides" src="pic3.jpg" />

<script>
var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  myIndex = getRandomInt(0, x.length - 1);
  x[myIndex].style.display = "block";  
  setTimeout(carousel, 2000); // Change image every 2 seconds
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
Fuzzy
  • 486
  • 3
  • 7