1

I'm using jQuery to update an image source

$("#myImage").attr("src", imagePath);

Immediately after, I try to detect the image's width with

$("#myImage").width();

Looks like sometimes (especially on first update) the update is not done, and I get invalid data.

Is there a way to make sure the image finished loading?

Ron Harlev
  • 16,227
  • 24
  • 89
  • 132

2 Answers2

4

$.load(); will fire on the image when it's finished loading:

$("img.myImage").load(function(){
  alert("My width is " + $(this).width());
});

Source: http://api.jquery.com/load-event/

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 2
    Indeed it will. Sadly I tested it before answering... :) Beat me to it. +1 – Doug Neiner Jan 16 '10 at 00:15
  • ...me too :( - http://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-something is a similar case. – bobwah Jan 16 '10 at 00:16
0

The image has a onload event like the document's body.

Make sure you set that event before you change the src.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088