Image width and height are zero due to asynchronous image loading

I have a long base64 type string that I get and I would like to set as src images

  $('#img').attr('src',base64data) console.log('height - ' $('#img').height()); console.log('width - ' $('#img').height()); 

It looks like im is returning 0 for height and width . Of course, if I wait a while I will get the right height.

The thing .attr() does not have a callback, how would I get information about getting the height and width after the src attribute is set, without returning 0 back. (I think I get 0 because the change in jQuery happens asynchronously, but I cannot be sure)

+4
source share
1 answer
 $('#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 for the load event. Note that I used the one() method, because if the image is already cached, it should not fire the load event twice

+11
source

Source: https://habr.com/ru/post/1413684/


All Articles