user3307017 user3307017 - 5 months ago 9
Javascript Question

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!

Answer

In vanilla JavaScript:

element.offsetHeight;

Make sure that your image is already loaded to get correct value. For this, either use load event of window instead of DOMContentLoaded event of document (or ready in jQuery), or preload your image via JS.