Ayro
Ayro

Reputation: 473

Get each image natural height with jQuery

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?

Upvotes: 23

Views: 36586

Answers (2)

Rohan
Rohan

Reputation: 3334

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);
};

Upvotes: 30

Wallace Vizerra
Wallace Vizerra

Reputation: 3542

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

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

   console.log($(this).prop('naturalHeight'));
});

Upvotes: 33

Related Questions