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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ayro
  • 473
  • 2
  • 5
  • 12

2 Answers2

33

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

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

   console.log($(this).prop('naturalHeight'));
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wallace Vizerra
  • 3,382
  • 2
  • 28
  • 29
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);
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rohan
  • 3,296
  • 2
  • 32
  • 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