Tomás Nicolorich
Tomás Nicolorich

Reputation: 17

Change multiple images src with jQuery

I have a grid of 2 rows and 3 columns and I want a different image in each card, also the images should be different depending if the user enters from different menus.

I've tried using a for loop to select different images but only selects the first or the las ones.

$("img").attr('src', function() {
  for (var i = 0; i < this.length; i++) {
    return "media/" + currentId + i + ".jpg";
    i++;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This is 1 card out of 6 -->

<div class="card">
  <div class="card-image waves-effect waves-block waves-light">
    <img class="activator">
  </div>
  <div class="card-content">
    <span class="card-title activator"></span>
  </div>
  <div class="card-action">
    <span class="link">Lorem impsum</span>
  </div>
  <div class="card-reveal">
    <span class="card-title"><i class="material-icons right">close</i></span>
    <p>Lorem impsum</p>
  </div>
</div>

As I've described earlier in the post, the output should be 6 different images and it's just 6 equal images.

Upvotes: 1

Views: 93

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

By providing a function to attr() you're creating an implicit loop through every img element. As such you don't need the for loop within that function. You then can get the index of the current element in the loop by receiving the first parameter to the function and using that as the name of the image file. Try this:

$("img").attr('src', function(i) {
  return "media/" + i + ".jpg";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This is 1 card out of 6 -->

<div class="card">
  <div class="card-image waves-effect waves-block waves-light">
    <img class="activator">
  </div>
  <div class="card-action">
    <span class="link">Lorem impsum</span>
  </div>
</div>
<div class="card">
  <div class="card-image waves-effect waves-block waves-light">
    <img class="activator">
  </div>
  <div class="card-action">
    <span class="link">Lorem impsum</span>
  </div>
</div>

Upvotes: 3

rollingthedice
rollingthedice

Reputation: 1125

You can set each image an id required for the corresponding source and using jQuery do:

$('.card img').each(function() {
    var path = 'media/' + $(this).attr('id') + '.jpg'
    $(this).attr('src', path);
});

Upvotes: 0

Related Questions