user3307017
user3307017

Reputation: 121

Get actual height of object whose set to "auto"

This seems like quite a rudimentary issue, but no matter how I phrase it, I can't seem to find anyone who's got a solution for me.

I have an image that's set size to fit my layout and to retain its aspect ratio, like so:

img{
   width:50%;
   height:auto;
}

Since I don't know how high the image is, I have to calculate another element's position using the real height of the image (The size that it's been resized to through auto).

$("img").height();

This returns 0 whenever it's set to auto, however. What am I missing? Or how can I find the current height of an image set to auto :)?

Thanks!

Upvotes: 1

Views: 3386

Answers (4)

Marat Tanalin
Marat Tanalin

Reputation: 14123

In vanilla JavaScript:

element.offsetHeight;

To get correct value, make sure your image is already loaded. For this, either use the load event of window, or preload your image via JS. Do not use the DOMContentLoaded event of document or ready in jQuery.

Upvotes: 5

gaetanoM
gaetanoM

Reputation: 42044

My proposal is:

$(function () {

  // in jQuery you can use: 
  var h = $("img").height();
  console.log('$("img").height() is: ' + h);
  console.log('$("img").css("height") is: ' + $("img").css("height"));
  

  // in javascript, with the unit measure:
  // This form corresponds to the second jQuery method
  var elem = document.querySelectorAll('img')[0];
  var h1 = window.getComputedStyle(elem).height;
  console.log('window.getComputedStyle(elem).height is: ' + h1);
});
img{
  width:50%;
  height:auto;
}
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<img src="https://www.google.it/logos/doodles/2016/karl-landsteiners-148th-birthday-5693101206142976-res.png">

Upvotes: 0

Midas
Midas

Reputation: 7131

You are probably using the "document ready" event while you should be using the load event. You cannot retreive the dimensions of an image before it has been rendered in the browser.

$(window).load(function() {
    $(window).resize(function() {
        console.log('Height: ' + $('img').height());
    }).resize();
});
img {
    width: 50%;
    height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://lorempixel.com/200/200" height="200" width="200">

Upvotes: 1

Pedro Mora
Pedro Mora

Reputation: 95

i think this would be helpful:

document.defaultView.getComputedStyle(document.querySelector("selector")).height;

It returns a string with the real height in px.

Upvotes: 1

Related Questions