width and height of image are zero because of asynchronous image loading

asynchronous, javascript, jquery

Solution

$('#img').one('load', function() {
   console.log('height - ' $(this).height());
   console.log('width - ' $(this).width());
})
.attr('src',base64data);

/* if this image is already cached load event couldn't be fired:
 * then look for "complete" status and trigger load event 
 */
if ($('#img').get(0).complete) {
   $('#img').trigger('load');
}

Before getting `width` and `height` you need to wait the `load` event. Note that I used `one()` method, because if the image is already cached it should not fire the `load` event twice

Problem

I have a long `base64` type string I get and I'd like to set as the `src` of the image ``` $('#img').attr('src',base64data) console.log('height - ' $('#img').height()); console.log('width - ' $('#img').height()); ``` It looks like im getting back `0` for both `height` and `width`. Of course if I wait a while then i'll get the proper height. The thing is `.attr()` doesn't have a callback, how would I get about getting the height and width after the `src` attribute is set without getting `0` back. (I think i'm getting 0 because the change in Jquery is happening asynchronously but I cant be too sure)

Original source