0

I'm trying to get the dimensions of some images. Sometimes I get the dimensions and sometimes I don't. I believe it's depends on whether the images have been loaded or not?

I'm trying to get the max width and height of the images in an element. This is the code:

        var maxImageHeight = 0;
        var maxImageWidth = 0;
        textElement.find("img").each(function() {
            console.log($(this).height());
            console.log($(this).width());
            if($(this).height() > maxImageHeight) {
                maxImageHeight = $(this).height(); 
            }
            if($(this).width() > maxImageWidth) {
                maxImageWidth = $(this).width(); 
            }
        });

Sometime the console.log output yields the correct dimensions and sometimes it's just 0.

I guess I somehow have to wait until all the images have been loaded? Thanks for any help.

Here is a jsfiddle example, which seems to work every time. https://jsfiddle.net/z0eayxfw/2/

S.A.
  • 99
  • 8
  • try image onload method textElement.find("img").on("load", function() { // do stuff }).each(function() { console.log($(this).height()); console.log($(this).width()); }); – R. S. Sep 14 '18 at 08:50
  • Thanks for the reply. I tried it, but the dimensions ends up being 0 using this as well? – S.A. Sep 14 '18 at 08:58
  • This solution: https://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached or this plugin https://github.com/desandro/imagesloaded resolves your issue – ReSedano Sep 14 '18 at 09:18
  • The imagesLoaded plugin worked like a charm. Thanks! – S.A. Sep 14 '18 at 09:48

0 Answers0