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.
The load
event works for Images:
$('img.userIcon').on('load', function () {
$(this).toggleClass( 'bigImg', $(this).height() > 100 );
});
Image objects allow attachment of onload event listeners:
var img = new Image;
img.onload = function () {
alert("Loaded");
};
img.src = "dummy-picture.png";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With