1

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!

user3307017
  • 121
  • 2
  • 13

4 Answers4

5

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.

Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52
1

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">
Midas
  • 7,012
  • 5
  • 34
  • 52
1

i think this would be helpful:

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

It returns a string with the real height in px.

Pedro Mora
  • 95
  • 9
0

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">
gaetanoM
  • 41,594
  • 6
  • 42
  • 61