15

I have the following line of javascritp $("#hero_image img").attr('src', src); to change an image. The following lines then do whatever they do based on the images new width which I was calling through $("#hero_image img").width();.

However, how do I ensure that this image has fully loaded before getting the width, otherwise I will be returned with the old width? Setting a timeout isn't reliable enough.

0

2 Answers 2

20

You can get the width in the .load() event handler which fires after it's fully loaded, like this:

$("#hero_image img").load(function() {
  alert($(this).width());
}).attr('src', src);

If you're doing this and re-using the image, either bind the .load() handler once, of you need different behavior each time use .one() so it doesn't keep adding an onload event handler:

$("#hero_image img").one('load', function() {
  alert($(this).width());
}).attr('src', src);
Sign up to request clarification or add additional context in comments.

2 Comments

Why to use one instead of on?
@SazzadHossainKhan so the handler only executes once, .one() has a very specific purpose - run then unbind.
2
$(function(){ // document ready
    $('#hero_image img').bind('load', function(){ // image ready
        // do stuff here
    });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.