23

I have to read each images' natural height and I should make calculations. However, I have some problem with read to natural height.

$('div.imgkirp img').each(function(){
    console.log($(this).naturalHeight);
});

It gets: (images number) undefined in console log. How can I read each of the images' natural height?

2 Answers 2

32

Try to use property naturalHeight of the image, using the prop method of jQuery:

$('div.imgkirp img').each(function(){

   console.log($(this).prop('naturalHeight'));
});
2
  • Tried this as well and it didn't work for me. Returns 'undefined'. Apr 3, 2017 at 18:16
  • 1
    @ArtlyticalMedia you should use load. Because if the image is not loaded, may be returned "undefined". Nov 9, 2017 at 10:46
30
var image = new Image();
image.src = $(this).attr("src");
alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);

This approach doesn't work in Internet Explorer 8 and below versions, because it doesn't support 'naturalWidth' and 'naturalHeight' properties. To achieve the same, use this code:

var image = new Image();
image.src = $(this).attr("src");
image.onload = function() {
  console.log('height: ' + this.height);
};
1
  • 1
    This just doesn't work. I've tried in Chrome and I can see that the source is correct; I set it to the new Image's src property and naturalHeight/naturalWidth 'undefined'. Apr 3, 2017 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.