Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  14] [ 5]  / answers: 1 / hits: 32202  / 14 Years ago, thu, november 4, 2010, 12:00:00

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.


More From » image

 Answers
39

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);

[#95073] Tuesday, November 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;