22

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 images' natural height ?

Ayro
  • 453
  • 2
  • 5
  • 12

2 Answers2

31

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

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

   console.log($(this).prop('naturalHeight'));
});
Wallace Maxters
  • 3,142
  • 2
  • 26
  • 28
30
var image = new Image();
image.src = $(this).attr("src");
alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);

This approach doesn't work in IE 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);
};
Rohan
  • 3,246
  • 1
  • 29
  • 35
  • 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'. – David Rhoderick Apr 03 '17 at 18:15