0

I have this javascript that's supposed to get the image's actual width and height. It works when I test locally on 127.0.0.1:8000 console logs on the snapshot enter image description here but on the server it fails enter image description here returns 0 as the image width and height.

Tried nesting the code in jquery ready but it does trigger before the image fully loads so I believe this is the issue.

here's the javascript

$(function() { 
    $(document).ready(function() { 
        $('.lynk-section img').each(function() {
            var width = $(this)[0].naturalWidth;
            console.log(width);
            //$(this).css('max-width', width+'px');

            var height = $(this)[0].naturalHeight;
            console.log(height);
            //$(this).css('max-height', height+'px');
        });
    });

});
Samuel M.
  • 127
  • 2
  • 14

3 Answers3

1

$(function() { and $(document).ready(function() { are the same thing (the first one is a shorthand), you only need one. But anyway, this will just wait for all the HTML code to be present in the page, not for the assets to be loaded. As @Rory said, window.load will wait for the images to be loaded, so you can then grab their dimensions.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

you have to use the onload event of the image, or maybe you just have to use window.onload event

//....
$('img').each(function() {
  $(this).on("load", function(){
    console.log("width: ", this.naturalWidth);
    console.log("height: ", this.naturalHeight);
  });
});
//....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/50x150">
<img src="http://via.placeholder.com/100x150">
<img src="http://via.placeholder.com/200x150">
alessandrio
  • 4,282
  • 2
  • 29
  • 40
0

Put your code under window load event.

$(function() { 
    $(document).on('load',function() {
        // Your code to measure image dimensions should go here.
    });
});
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
  • You're correct that you need the `window.load` event, however your code example doesn't do this. – Rory McCrossan Sep 18 '17 at 14:42
  • @RoryMcCrossan, I just gave him important clue. He has to write code where I have mentioned as comment. – Himanshu Upadhyay Sep 18 '17 at 17:55
  • A 'clue' isn't an answer though - and placing code where your comment is won't help. You've attached the load handler to the document, not the window, which is the important distinction. You need to run the code once the *window* has loaded as only then are the image dimensions available to be read in JS. – Rory McCrossan Sep 18 '17 at 17:57
  • yea, @RoryMcCrossan, you are right. I am learning from you. :-) – Himanshu Upadhyay Sep 18 '17 at 18:02