Kyle Underhill
Kyle Underhill

Reputation: 109

jQuery - Retrieve images randomly from an array on load

I'm trying to retrieve images from an array and randomly populate the src of each item on load but the images return as [object Object].

$(document).ready(function() {
  var imagesArray = [{
      id: "one",
      src: "https://cdn.shopify.com/s/files/1/1450/6394/products/MCS10014LS_MOCK_UP_1024x1024.png?v=1545018000"
    },
    {
      id: "two",
      src: "https://assets.bigcartel.com/product_images/191933374/tank_bikes_not_war_american_apparel__tri-oatmeal_mockup.png"
    },
    {
      id: "three",
      src: "https://cdn.shopify.com/s/files/1/0617/7613/products/Allday-No-Saint-Hockey-Jersey-MOCK_1024x1024.png?v=1492726972"
    }
  ];

  $(".item").each(function() {
    var randomImage =
      imagesArray[Math.floor(Math.random() * imagesArray.length)];
    $(this)
      .find("img")
      .attr("src", randomImage);
  });
});
.item {
  border: 2px solid;
  height: 40px;
  width: 40px
}

.item img {
  max-height: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>
<div class="item">
  <img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>
<div class="item">
  <img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>

Upvotes: 0

Views: 15

Answers (1)

Chris Heald
Chris Heald

Reputation: 62648

The result of sampling your images array is an object like:

{
  id: "one",
  src: "https://cdn.shopify.com/s/files/1/1450/6394/products/MCS10014LS_MOCK_UP_1024x1024.png?v=1545018000"
}

You just need to reference the correct property from it:

.attr("src", randomImage.src);

You're seeing [object Object] because the attribute value is being cast to a string when it's assigned, and object.toString() is the string literal "[object Object]":

({id: "one", src: "foo"}).toString()
"[object Object]"

Upvotes: 1

Related Questions