How can I check if a scrollbar is visible?
This nifty hasScrollbar function checks for both vertical and horizontal scrollbars. Feed your element to this function, and if it burps out true, then voila! Your element has a viewport-shy guest hiding — a scrollbar.
Diving deeper: Exploring scrollbar visibility
Detecting vertical scrollbar
To find out if an element has a vertical scrollbar, simply pit its scrollHeight against its clientHeight. If scrollHeight boxes its way to a victory (i.e., is greater), you've got yourself a scrollbar.
Spotting horizontal scrollbar
The same logic applies to the horizontal counterpart of our scrollbar friend — scrollWidth arm-wrestles clientWidth. If scrollWidth flexes its muscles (is larger), a scrollbar pops into existence.
Automatic scrollbar alerts
Life's too short to keep checking for scrollbar changes. Automate this task! Use event listeners to alert users when a scrollbar appears on a specific element:
Crafting a repeat-use scrollbar checker
Being a developer means being lazy efficient. Create a scrollbar checker tool. Demote your code from a one-time gimmick to an industrious, labor-saving plugin.
Feeling padded: Dealing with the padding effect
ClientHeight and clientWidth include the element's padding. But don't let padding dupe you when dealing with CSS:
Living on the edge: Dynamic content and scrollbars
Dynamic content tends to be a boisterous party crasher, summoning a scrollbar out of nowhere. Use event listeners, or hire a MutationObserver, to keep an eye on these unruly DOM changes:
Plug & Play: jQuery style
Take the scenic jQuery route instead of climbing the steep slopes of pure JavaScript:
Just remember, as attractive as jQuery's brevity is, it may not be the ideal tour guide for all projects.
Was this article helpful?