views:

243

answers:

2

I have a function resizePreview() that will resize an image in a jQuery dialog box if the image is too big. This image can be changed by the user. My code goes something like this:

$('#imagePreview').attr('src', newImageSrc);
resizePreview();

resizePreview() uses $('#imagePreview').width() and .height() to get the dimensions and resizes accordingly. The problem is that the new image isn't loaded by the time resizePreview() is called so the image is resized according to it's original dimensions, not according to the dimensions of the newly loaded image.

If I put an alert() call in between the two lines of code it works (since the alert gives the browser enough time to load the new image). Apparently I should use an event? Is there an existing event, or is there a way I can make one, for when the image src has changed (sort of like an onChange event, but for that attribute) or for when the new image has completed loading? Thanks for your time.

+2  A: 

Image objects allow attachment of onload event listeners:

var img = new Image;
img.onload = function () {
    alert("Loaded");
};
img.src = "dummy-picture.png";
Ionuț G. Stan
Thanks for your help!
CMB
+2  A: 

$.load() works for Images.

http://docs.jquery.com/Events/load#fn

$('img.userIcon').load(function(){
  if($(this).height() > 100) {
    $(this).addClass('bigImg');
  }
});
Jonathan Sampson
Got it to work, thanks!
CMB