RhymeGuy
RhymeGuy

Reputation: 2112

Image load function not working

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>

Upvotes: 1

Views: 407

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

Upvotes: 2

Related Questions