Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event for when image 'src' attribute is changed?

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.

like image 804
CMB Avatar asked Aug 18 '09 15:08

CMB


2 Answers

The load event works for Images:

$('img.userIcon').on('load', function () {
    $(this).toggleClass( 'bigImg', $(this).height() > 100 );
});
like image 148
Sampson Avatar answered Nov 07 '22 17:11

Sampson


Image objects allow attachment of onload event listeners:

var img = new Image;
img.onload = function () {
    alert("Loaded");
};
img.src = "dummy-picture.png";
like image 33
Ionuț G. Stan Avatar answered Nov 07 '22 17:11

Ionuț G. Stan