7

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.

Alex
  • 8,353
  • 9
  • 45
  • 56
Locke Donohoe
  • 482
  • 1
  • 7
  • 22
  • 1
    scrollHeight and clientHeight should be the same if the body is full height or higher, right? – Shomz Jun 04 '15 at 11:23
  • http://stackoverflow.com/questions/2146874/detect-if-a-page-has-a-vertical-scrollbar – Tirma Jun 04 '15 at 11:25
  • Try `window.innerHeight` `document.body.scrollHeight > window.innerHeight` – artm Jun 04 '15 at 11:25
  • see [my working solution](https://stackoverflow.com/a/71170105/3591273) to determine if an element is **actually scrollable** – Nikos M. Feb 18 '22 at 08:01

2 Answers2

4

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

Alex
  • 8,353
  • 9
  • 45
  • 56
  • I added `height: 100%;` to the body and this appears to have changed nothing, although your JS fiddle works. Not sure what's happening. – Locke Donohoe Jun 04 '15 at 11:52
  • @LockeDonohoe it needs to be on `html` also. – Alex Jun 04 '15 at 11:53
  • 1
    I realised this right after I posted, decided to test it, and I finally managed to get it to work by changing the operator to `<=`, what it should be for the script to work as intended. Thank you. – Locke Donohoe Jun 04 '15 at 12:05
-2

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.

Shomz
  • 37,421
  • 4
  • 57
  • 85