Explain Codes LogoExplain Codes Logo

How can I check if a scrollbar is visible?

javascript
event-listeners
scrollbar-detection
dom-manipulation
Nikita BarsukovbyNikita Barsukov·Nov 11, 2024
TLDR
const hasScrollbar = el => el.scrollWidth > el.clientWidth || el.scrollHeight > el.clientHeight; console.log(hasScrollbar(document.querySelector('.element')));

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.

// Here's a magic trick to make a vertical scrollbar appear! const hasVerticalScrollbar = el => el.scrollHeight > el.clientHeight;

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.

// Now watch as I pull a horizontal scrollbar out of my hat! const hasHorizontalScrollbar = el => el.scrollWidth > el.clientWidth;

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:

// The scrollbar alarm system, alerting when it sees a scrollbar intruder const element = document.querySelector('.watched-element'); element.addEventListener('mouseover', () => { if (hasScrollbar(element)) { alert('Scrollbar has crashed the party!'); } });

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.

// This diligent worker checks for vertical and horizontal scrollbars at your whim, // tirelessly complying even if you've had too much coffee and can't tell up from down. const ScrollbarDetector = { vertical: el => el.scrollHeight > el.clientHeight, // "Vertical scrollbar detected! Just doing my duty, sir." horizontal: el => el.scrollWidth > el.clientWidth, // "Why yes, there's a horizontal scrollbar here! No need to thank me, sir." }; console.log(ScrollbarDetector.vertical(document.querySelector('.element'))); // "Has a scrollbar shown up to the party? Let me check."

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:

// Unmasking the padding decoy const getClientHeight = el => { const computedStyle = getComputedStyle(el); return el.clientHeight - parseFloat(computedStyle.paddingTop) - parseFloat(computedStyle.paddingBottom); };

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:

// The vigilant MutationObserver, always on duty const observer = new MutationObserver(mutations => { mutations.forEach(() => { if (hasScrollbar(element)) { // Handle scrollbar's unexpected arrival } }); }); observer.observe(document.querySelector('.dynamic-content'), { childList: true, subtree: true });

Plug & Play: jQuery style

Take the scenic jQuery route instead of climbing the steep slopes of pure JavaScript:

// jQuery: Brevity is the soul of scrollbar detection const hasJQueryScrollbar = el => $(el).prop('scrollHeight') > $(el).innerHeight();

Just remember, as attractive as jQuery's brevity is, it may not be the ideal tour guide for all projects.