santa
santa

Reputation: 12512

Calculate height of the element w/ jQuery

I need to assign a height to an element based on the height of the screen. I have content going past the screen fold, so I can not use

$(window).height();

Is there a way to calculate the height of the visible part of the open window?

Upvotes: 0

Views: 140

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337713

To get the visible height of the element you would subtract the offetTop of the element from the height of the window.

var elTop = $("#element").offset().top;
var winHeight = $(window).height();
var elVisibleHeight = winHeight - elTop;

If elVisibleHeight < 0 then the element is below the screen fold and not visible. If you needed to keep track of the element's position, you'd need to update this on window scroll.

UPDATE

I've created a fiddle with a working example of the theory. Obviously you can shorten this, I've left it pretty verbose so it's more clear as to what is happening.

Example Fiddle

Upvotes: 2

Jay
Jay

Reputation: 1404

This will show you the difference of document or window height.

http://jsfiddle.net/9YFwx/

Upvotes: 2

Stuart Burrows
Stuart Burrows

Reputation: 10814

Another way to do it is like so:

var height = window.innerHeight || document.documentElement.clientHeight || getElementsByTagName('body')[0].clientHeight;

This will fallback based on browser support

Upvotes: 3

Related Questions