Morvael
Morvael

Reputation: 3567

Get actual content height with Javascript (or jQuery)

There are many ways of getting the height of a document, but due to different browser implementations most of them (I believe) return the highest of a number of values ... which is fine most of the time.

In my case I have a number of elements on the page that I know to be a smaller height than the window and viewport heights. What I'm trying to get is the actual height of all the rendered elements.

Things that don't work (with testing in Firefox):

  1. $(document).height(); // gives the window height
  2. document.body.scrollHeight; // gives 7, its always 7 I don't know why
  3. document.body.offsetHeight; // also gives 7
  4. document.documentElement.clientHeight; // sometimes gives window height
  5. document.documentElement.scrollHeight; //gives window height
  6. document.documentElement.offsetHeight; generally gives a value in the range of 23

At present I'm thinking that the way around this might be to insert a div with height: 0 at the bottom of my page and grab $(div).offset().top, but I feel that this is highly likely to go wrong at some point in the future.

So before I do that ...

Is there a way of knowing the content height when it's less than the window height?

EDIT:

People have asked for clarification. Heres a jsFiddle example of what I want / the results I'm getting. https://jsfiddle.net/8Lu2zcw8/1/

Running that results in the same value for Win Height: and Doc Height being written out to the console.

EDIT2:

My issue was due to the body not wrapping the content correctly due to floated and absolutely positioned elements, as pointed out by @tim-vermaelen in the comments to his solution.

Upvotes: 0

Views: 2285

Answers (2)

Tim Vermaelen
Tim Vermaelen

Reputation: 7069

I suggest you use $(document.body).height().

In CSS you have to put:

html,
body { height: 100%; }

This will only give correct results in case of body padding, margin and borders of the body element are 0. When direct children are floating or put on position absolute, the height of these elements doesn't count. Hence for floating elements you always clearfix the parent to solve these wrapping issues.

If not you can use $(document.body).outerHeight(includeMargin)

Upvotes: 2

Patrik Krehák
Patrik Krehák

Reputation: 2683

$(document).height() will give you content size, not window's. If it gives you window's size, then you probably messed up your CSS. Also, you can try $('body').height()

Upvotes: 0

Related Questions