Reputation: 492
I have a piece of JS code that determines whether there is a vertical scrollbar and applies a CSS class to an element. Nothing big.
What is confusing me is it appears to be doing the opposite of what I understand it should be doing. This isn't a problem unless it is a bug and is fixed in the future.
The code:
if (document.body.scrollHeight > document.body.clientHeight) {
var d = document.getElementById("footer").className = "footernoscroll";
}
My understanding is that it will apply the class if there is a vertical scroll bar, but it appears to be applying the class if there isn't a scroll bar. Am I interpreting this correctly and the code is acting strangely or is my interpretation wrong?
EDIT: Thought I should add, if I reverse the operator the effects will be reversed and it will use the else
part of the statement instead.
Upvotes: 8
Views: 15958
Reputation: 37701
The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar.
Taken from here: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
So it means the values are the same if there is no scrollbar, and scrollHeight
is greater when there is one.
Upvotes: -2
Reputation: 8663
Make sure that your body is 100% of the window height. If you don't have this then the clientHeight
value will be the combined height of the items within body
and not the full window height, whereas scrollHeight
will be the full height of the window.
Here's a fiddle that shows it working (open dev tools and view console): http://jsfiddle.net/alexcoady/c53d7q27/1/
html, body {
height: 100%;
padding: 0;
margin: 0;
}
clientHeight documentation
scrollHeight documentation
Upvotes: 5