jQuery - Detect if element height is bigger than window height and do something about it
Asked Answered
D

3

5

The tittle really says it all.

Basically i want to detect if this div's height is bigger than window height and do something about it..

I have done this but i cant get it to work http://jsfiddle.net/dhkCa/3 Why wont it work?

Edit: Fixed a little error in the css code. Jsfiddle link updated.

Discovery answered 31/8, 2011 at 16:8 Comment(1)
if you alert the 2 values, you'll notice that the document height appears to be 20px greater than the div height example hereTransmissible
S
22

The document's contains all the elements within itself, and its height is a sum of the heights of all those elements (all the display:block elements anyway, plus margin and padding); therefore no contained element can be taller than the document itself. What you need to do is compare the window's height, not the document's:

var div = $("div").height();
var win = $(window).height();

if (div > win ) {
    $("div").addClass('red');
}

JS Fiddle demo.

Stability answered 31/8, 2011 at 16:11 Comment(1)
Right.. That is also clearly stated jquery api.. Once again I just failed to comprehend what I read. Thanks ( +1 ) and will be accepting when i can.Discovery
T
1

For an element that has a scroll height that's different than the document's scroll height, you can use element.getBoundingClientRect().height (Docs).

Thornton answered 25/1, 2018 at 13:39 Comment(0)
P
1

I would suggest to use .outerHeight(), since .height() doesn't look at the padding of an element.

var div = $("div").outerHeight();
var win = $(window).height();

if (div > win ) {
    $("div").addClass('red');
}
Photoelectrotype answered 21/12, 2022 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.