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>