I have this website where when you refresh it will bring up a random image from multiple JS array inside multiple divs (each div has its own JS array with different images). The problem is that my code is only using the last declared JS array and uses the same 2 pictures for all the divs.
$('.random-image-container').each(function() {
var container = $(this)
$('<img class="random-image" src="' + images[Math.floor(Math.random() * images.length)] + '">').appendTo(container);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<article class="grid-item">
<div class="random-image-container">
<script>
var images = ['IMG/1.jpg', 'IMG/2.jpg'];
</script>
</div>
</article>
<article class="grid-item">
<div class="random-image-container">
<script>
var images = ['IMG/3.jpg', 'IMG/4.jpg'];
</script>
</div>
</article>
<article class="grid-item">
<div class="random-image-container">
<script>
var images = ['IMG/5.jpg', 'IMG/6.jpg'];
</script>
</div>
</article>
<article class="grid-item">
<div class="random-image-container">
<script>
var images = ['IMG/7.jpg', 'IMG/8.jpg'];
</script>
</div>
</article>
can someone help me with this ?
2
Answers
The problem is because you’re re-declaring the same variable in each
<script>
block – you’re not appending/pushing to the array. I’d suggest you change the data structure which holds your image path/filenames in to an object or 2D array instead, and crucially, only define it once.Here’s an example of how your code would look if you update it to use a 2D array to store the images, with each element of the parent array equating to each
.random-image-container
:Note that the
alt
attribute was only added to this example to make it clear which image is intended to be shown.This seems to be related to the scope of the ‘images’ variable.
Each <script> block is overwriting the previous one, being that as a result, only the last array is being used in your jQuery function.
You have several possible solutions:
<div class="random-image-container" data-images='["IMG/1.jpg", "IMG/2.jpg"]'></div>
Hope this helps.
And then, add to your jQuery loop:
var images = JSON.parse(container.data('images')); //this will access your data-images attribute data