Yeti
Yeti

Reputation: 5818

Replacing image src, once image is loaded

I have this code which fades in multiple images only after they are loaded. It is triggered even when image is loaded from the cache.

$(".image-class").one("load", function() {
    $(this).fadeIn("slow");
}).each(function() {
    if(this.complete) $(this).load();
});

Now, when the load completes, if the width of the image is less than 130, I want to load another image in it's place. Nothing is to be shown until the 2nd image is loaded.

$(imgID).one("load", function() {
    // check if image is too small
    if($(this).width() < 130 ){
        $(this).attr("src","larger_image.jpg");
    }else{
        $(this).fadeIn("slow");
    }
}).each(function() {
  if(this.complete) $(this).load();
});

This does load a different photo if width < 130. But it never seems to trigger load for the 2nd image. The fadeIn never triggers for the 2nd image, so it's never shown.

How can this be fixed?

Upvotes: 0

Views: 51

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Because you are using .one() to register the handler, which will trigger the handler only once after which the handler is discarded

var imgID = 'img';
$(imgID).on("load", function() {
  // check if image is too small
  if ($(this).width() < 130) {
    $(this).attr("src", "//placehold.it/150x64");
  } else {
    $(this).fadeIn("slow").off('load');
  }
}).hide().each(function() {
  if (this.complete) $(this).load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="//placehold.it/64x64" />

Upvotes: 3

Related Questions