mardi 14 novembre 2023

jquery random image arrays inside divs

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 ?




Aucun commentaire:

Enregistrer un commentaire