-1

I have this JS code which includes an array of (currently) 4 images and a function that chooses a random image:

    const scenes = ['url(scenes/scene1.jpg)', 'url(scenes/scene2.jpg)', 'url(scenes/scene3.jpg)', 'url(scenes/scene1.jpg)'];

    function randomScene() {
        const shuffle = Math.floor(Math.random() * (scenes.length));
        document.getElementById('bg-switch').style.backgroundImage = scenes[shuffle];
    };

Then I have an HTML button - if clicked, it executes "randomScene()", and displays an image from the array called "scenes".

    <section id="bg-switch">
        <div class="container text-center">
            <a><button type="button" onclick="randomScene()">Click!</button></a>
        </div>
    </section>

Problem: I would like to avoid showing the same image twice in a row when the button is clicked.

  1. I'd like to remove already shown images from the array.
  2. I'd like to reset (shuffle?) the array, once all elements were removed from it, so clicking the button keeps displaying images.
Wolfenek
  • 45
  • 1
  • 5
  • Easiest way might be to [sort the array randomly](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array), then just step through it in order. – Daniel Beck Nov 06 '18 at 15:07
  • I would do it the way Daniel suggested. Shuffle the array, then you can iterate through it without worrying about repetition or randomization or cleanup anymore. – IceMetalPunk Nov 06 '18 at 15:29

1 Answers1

0

You can create a variable and store the image path in that. On every click check if the current image is same as randomly generated image. If not then add that to background and update the currImg variable

const scenes = ['url(scenes/scene1.jpg)', 'url(scenes/scene2.jpg)', 'url(scenes/scene3.jpg)', 'url(scenes/scene1.jpg)'];

let currImg = ''

function randomScene() {
  const shuffle = Math.floor(Math.random() * (scenes.length));
  if (scenes[shuffle] === currImg) {
    randomScene()
  } else {
    document.getElementById('bg-switch').style.backgroundImage = scenes[shuffle];
    currImg = scenes[shuffle]
  }
};
<section id="bg-switch">
  <div class="container text-center">
    <a><button type="button" onclick="randomScene()">Click!</button></a>
  </div>
</section>
brk
  • 48,835
  • 10
  • 56
  • 78
  • Thanks. Now it doesn't choose the same image twice in a row. I should also try the method suggested by Daniel Beck & IceMetalPunk (looping through the entire array), but your solution was a big step forward for me! – Wolfenek Nov 08 '18 at 12:47