0

Overview:

I've created bit of jQuery that randomizes (4) images in a folder, within an array on click. This is working, but I cannot track down why "undefinied" is returned on the image URL string randomly, creating a broken image link.

Goal:

I am looking for a way to tell my function there are only 4 images, and of course - stop randomly returning "undefined". It would also be nice if it didn't repeat the same image twice in two clicks, but this is out of scope of the request I suspect - if so ignore.

Note: sometimes you have to click through a bit to get it to break.

Thank you!

/* ======================================
 IMAGE RANDOMIZER Scripts 
 ========================================= */ 
jQuery(function($){ 
 // Array of Images 
 var myImages = [
  'nessie-icons_nessie-teal.svg',
  'nessie-icons_nessie-pink.svg',
  'nessie-icons_nessie-yellow.svg',
  'nessie-icons_nessie-light.svg'
 ];
 
   // select a element with id="the-img-id"
    $('#imageRando').click(function() {
      var randomInt = Math.round(Math.random() * myImages.length-1      ); // Create random number
      this.src = 'https://nessiedrinks.wpengine.com/wp-content/themes/Divi-child/nessie-icons/'+myImages[randomInt]; // replace the src with the new img
    });
});
/* ========================================= 
IMAGE RANDOMIZER Styles
========================================== */
#imageRando {
   width: 40%;
    text-align: center;
    margin: 0 auto;
    position: fixed;
    margin-left: 5%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ========================================= 
IMAGE RANDOMIZER Markup
========================================== -->
<div class="social-wrap">
  <img id="imageRando" src="https://nessiedrinks.wpengine.com/wp-content/themes/Divi-child/nessie-icons/nessie-icons_nessie-teal.svg" />
</div>
Birdie Golden
  • 505
  • 6
  • 20
  • 2
    https://jsfiddle.net/45byh92g/ Your random number logic some times goes negative. – Taplar Apr 16 '20 at 18:46
  • Does this answer your question? [How to efficiently randomly select array item without repeats?](https://stackoverflow.com/questions/17891173/how-to-efficiently-randomly-select-array-item-without-repeats) – Heretic Monkey Apr 16 '20 at 18:50
  • `Math.round(Math.random() * 3)` achieves what you want. – EternalHour Apr 16 '20 at 18:56

1 Answers1

2

Your randomizer implementation (Math.round(Math.random() * myImages.length-1)) is returning -1 sometimes. This results in accessing index -1 of the myImages array which is undefined.

What you want is Math.floor(Math.random()*myImages.length). This will result in indexes from 0 through 3 for your myImages array of length 4. This is because Math.random returns 0 to 1 (0 inclusive and 1 exclusive).

dillon
  • 721
  • 6
  • 16