javascripthtmlimageimagemap

How to make sure random images don't repeat in a row


I've been working on a script where when someone clicks on the image it will bring up a random image. For the purpose of explanation, I have a very basic example I put in codepen with some door images with numbers on them.

I have been able to get everything to work to randomize the images with the onclick, but sometimes images repeat back to back so you have to click the button a couple times for a new image to pop up.

For example, when someone clicks the picture, the randomized picture that shows up can be in the order of image 1, image 4, image 4, image 3. Just as a general example.

What do I need to do in order to stop showing pictures back to back? I don't mind if the pics show up again, just not directly back to back as it makes the user have to click the button multiple times for the image to change.

I've tried looking through different threads but nothing I found seemed to work on my end.

HTML

<body>
       <div onLoad="pickimg2">
 
    <img src="https://websitetestsone.neocities.org/images/door-test-default.png" name="randimg" border=0 usemap="#image_map">
<map name="image_map">
  <area alt="" title="" href="" coords="180,378,335,407" shape="rect" onClick="pickimg2();return false;">
</map>
</div>

Javascript

var myImages1 = new Array();
myImages1.push("https://websitetestsone.neocities.org/images/door-test-1.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-2.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-3.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-4.png");
myImages1.push("https://websitetestsone.neocities.org/images/door-test-5.png");

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function pickimg2() {
  document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}

Codepen link https://codepen.io/hrussio/pen/PogdPom

Thanks!


Solution

  • Track the index of the last image shown so you can ensure it does not repeat.

    var lastImageIndex = -1; // Initialize last shown image index = -1
    
    function pickimg2() {
      var randomIndex;
      do {
        randomIndex = getRandomInt(0, myImages1.length - 1);
      } while (randomIndex === lastImageIndex); // Generate random index until different from last index
      document.randimg.src = myImages1[randomIndex];
      lastImageIndex = randomIndex; // Update last shown image index
    }