RH2019
RH2019

Reputation: 119

Images loading twice with jQuery

I have used jQuery to display images from a JSON file. However the 2 images appear twice when I only want to display one of each.

JSON:

{
  "tiles": [
   {
     "city": "example",
     "img" : "example.jpg"
   },
   {
     "city": "example",
     "img" : "example.jpg"
   }
  ]
}

HTML:

<div class="tile-image"></div>
<div class="tile-image"></div>

CSS:

.tile-image img {
  width: 432px;
  height: 192px;
  object-fit: cover;
  border-radius: 4px;
}

jQuery:

jQuery(document).ready(function ($) {
  var jsonURL = "example.json";
  $.getJSON(jsonURL, function (json) {

    var imgList = "";

    $.each(json.tiles, function () {
      imgList += '<div><img src= "' + this.img + '"></div>';
    });

    $('.tile-image').append(imgList);
  });
});

I have tried removing the two div containers from my HTML but when I do this all the images disappear. Any suggestions as to why they are appearing twice instead of once would be great.

Upvotes: 1

Views: 223

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you append the imgList to all .tile-image elements.

To fix this you could instead loop over the .tile-image and append the img from the response data at the matching index, like this:

// mock AJAX response:
var response = {
  "tiles": [{
    "city": "example",
    "img": "example-1.jpg"
  }, {
    "city": "example",
    "img": "example-2.jpg"
  }]
}

jQuery(function($) {
  // inside the AJAX callback...
  // $.getJSON('example.json', function (response) {
    $('.tile-image').each(function(i) {
      $(this).append('<div><img src= "' + response.tiles[i].img + '"></div>');
    });
  // });
});
.tile-image img {
  width: 432px;
  height: 192px;
  object-fit: cover;
  border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tile-image"></div>
<div class="tile-image"></div>

Upvotes: 1

Related Questions