Issue
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 ?
Solution
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:
- Declare a different variables for each array (Eg.: var images1 = ['IMG/1.jpg', 'IMG/2.jpg']; var images2....)
- Add a data-images attribute to your "random-image-container" div with your images arrays
<div class="random-image-container" data-images='["IMG/1.jpg", "IMG/2.jpg"]'></div>
And then, add to your jQuery loop:
var images = JSON.parse(container.data('images')); //this will access your data-images attribute data
Answered By - cMendes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.