-1

I have here a simple program that displays random images that are in order, with two buttons that enable you to switch from an ascending order and then descending order. Now, I want to implement a random button that will display a random image of the selection but, I can't seem to figure out how. Below is my code:

var images = [
  "1.jpg",
  "2.jpg",
  "3.jpg",
  "4.jpg",
  "5.jpg",
  "6.jpg",
  "7.jpg",
  "8.jpg"
];

var num = 0;

function next() {
  var slider = document.getElementById("slider");
  num++;
  if (num >= 8) {
    num = 0;
  }
  slider.src = images[num];
}


function prev() {
  var slider = document.getElementById("slider");
  num--;
  if (num < 0) {
    num = 7;
  }
  slider.src = images[num];
}

function random() {
  //where the code is supposed to be
}
<head>
  <title>Laboratory Exercise 7</title>
</head>

<body>
  <div>
    <button onClick="prev()"> &lt;--- </button>
    <img id="slider" SRC="1.jpg" width="200px" height="100px" />
    <button onClick="next()"> ---&gt; </button>
    <button onClick="random()"> Random </button>
  </div>
</body>
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
  • 1
    Does this answer your question? [random number js min max](https://stackoverflow.com/questions/38126901/random-number-js-min-max). Just get a random index and show image with this index – Omri Attiya Nov 28 '20 at 09:43

1 Answers1

0

There are your problem decission:

function random(min, max) {
  return Math.round(Number(min + Math.random() * (max - min)));
}

function random() {
  var slider = document.getElementById("slider");  
  slider.src = images[random(0, 7)];
}

The first function is returning random number from 0 to 7 (all your images in arrays) and after that the second function set random number like index and take a image from the array with that index.

But you also can minimaze your code like that, just take out slider variable outside every function.

var slider = document.getElementById("slider");

I hope that it will help to you!