1

GOAL: Red borders should became green once image in .thumbnail div is loaded

JSFIDDLE: https://jsfiddle.net/3k8xy2cf/

var container;
var img;

$("#products .thumbnail").each(function() {
  container = $(this);
  img = new Image();
  img.src = $(container).find('img').attr('src');
  img.onload = function() {
    $(container).addClass('loaded');
  }
});
.product {
  float: left;
  border: 5px solid red;
}
.product.loaded {
  border-color: green;
}
.product img {
  width: 25%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="products">
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/600x600" alt="">
    </div>
  </div>
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/800x800" alt="">
    </div>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
RhymeGuy
  • 2,102
  • 5
  • 32
  • 62
  • 2
    Your container is scoped outside the each method. It's value will be the same for all the load events, and be the last element. Scope that variable to the each method. – Taplar Jun 15 '18 at 14:55
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Taplar Jun 15 '18 at 14:56
  • Also side note, the container is already a jQuery object due to you doing `$(this)` so there is no point in re-wrapping it. – Taplar Jun 15 '18 at 14:56
  • Also swap the onload and the .src lines – mplungjan Jun 15 '18 at 14:59
  • @Taplar Thanks for explanation! Got it https://jsfiddle.net/4rx7wvmz/ – RhymeGuy Jun 15 '18 at 15:02

1 Answers1

2

Your code is a lot more complicated than it needs to be. You don't need the each() loop and you certainly don't need to create a new img element from the ones which already exist.

Instead you can just use a load() event handler on the img elements which adds the class to the parent .thumbnail, like this:

$('#products .thumbnail img').on('load', function() {
  $(this).closest('.thumbnail').addClass('loaded');
});
.thumbnail {
  border: 2px solid #C00;
}

.thumbnail.loaded {
  border-color: #0C0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="products">
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/125x125" alt="">
    </div>
  </div>
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/150x150" alt="">
    </div>
  </div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339