Sometimes, we want to check whether HTML element has scrollbars with JavaScript.
In this article, we’ll look at how to check whether HTML element has scrollbars with JavaScript.
How to check whether HTML element has scrollbars with JavaScript?
To check whether HTML element has scrollbars with JavaScript, we check if the scrollHeight of the element is bigger than its clientHeight.
And we check if scrollWidth of the element is bigger than its clientWidth.
For instance, we write
const div = document.getElementById("div-id");
const hasHorizontalScrollbar = div.scrollWidth > div.clientWidth;
const hasVerticalScrollbar = div.scrollHeight > div.clientHeight;
to select the element with getElementById.
Then we check if the body element’s scrollHeight is bigger than its clientHeight to check if the body element has a vertical scrollbar.
Likewise, we check if the body element’s scrollWidth is bigger than its clientWidth to check if the body element has a horizontal scrollbar.
Conclusion
To check whether HTML element has scrollbars with JavaScript, we check if the scrollHeight of the element is bigger than its clientHeight.
And we check if scrollWidth of the element is bigger than its clientWidth.