1

I have a responsive layout with some images. The images have max-width:100% set. And the height cannot be preset in the CSS or the HTML height attribute, or else the image distorts as the responsive layout gets smaller. It has to be height: auto; in order to scale properly.

Is it possible to calculate the height of the image in jQuery? .height() and .css('height') relies on the css or height attrib to be set, and like I said, I cannot set those without distorting the image when the responsive design changes size.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • duplicate - see http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser – TheHe Sep 04 '12 at 03:42

3 Answers3

3

My problem ended up being that .height() and .css('height') were returning 0 because the image(s) had not loaded yet when that code was called.

In order to get the height, I ran the following:

$(document).ready(function(){
  $('img.whatever').load(function(){
    console.log($(this).height()); // calculates height correctly after image is loaded.
  });
});
Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • This is a great, common sense solution. Worked great for me, as I was having the same issue (but for some reason mine was only in Firefox). – Tricky12 Mar 22 '14 at 17:31
1

You can use outerHeight()

http://api.jquery.com/outerHeight/

zenkaty
  • 1,538
  • 9
  • 11
0

As mentioned in Determine original size of image cross browser? :

You have 2 options:

Option 1:

Remove the width and height attributes and read offsetWidth and offsetHeight

Option 2:

Create a JavaScript image object, set the src, and read the width and height (you don't even have to add it to the page to do this).

function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    alert ('The image size is '+width+'*'+height);
    }

    newImg.src = imgSrc; // this must be done AFTER setting onload

}

I am sure that solution will work for you.

If you just change the height, or width of the image, it should not distort the aspect ratio.

Community
  • 1
  • 1
ShaunOReilly
  • 2,186
  • 22
  • 34