Skip to content Skip to sidebar Skip to footer

Detect If Scrollbar Is Visible (e.g. On A Mobile Device)

I've seen lots of questions/answers regarding detecting if an HTML element is scrollable (e.g. Detect scrollbar dynamically ). I need something similar, but not quite the same. I h

Solution 1:

JS solution: Compare the height (offsetHeight or clientHeight) of the element wrapping the content and the list itself -- then execute code accordingly.

If you want to detect a scrollbar, this stackoverflow answer may help: Hide scroll bar, but while still being able to scroll

Where you can do Element.offsetWidth - Element.clientWidth to get a scrollbar's width (it should return 0 if there is no scrollbar).

This Stack Overflow answer goes into detail about offset vs. client: What is offsetHeight, clientHeight, scrollHeight?

const listWrapper = document.getElementById('list-wrapper'),
      container   = document.getElementById('container'),
      list        = document.getElementById('list');

// compare the height of the target element ( listWrapper or list )// against the element containing the element ( container )if( list.offsetHeight > container.offsetHeight ){
  // if the list is longer, add a class to the containing element
  container.className = 'overflowed';
}

console.log( container.offsetHeight - container.clientHeight );
console.log( listWrapper.offsetHeight - listWrapper.clientHeight );
#container{ height: 150px; width: 150px; overflow-y: scroll; border: solid 1px red; }
#container.overflowed{
  background: linear-gradient(transparent 85%, rgba(0,0,0,0.25) );
}
<divid="container"><divid="list-wrapper"><ulid="list"><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li><li>abcde</li></ul></div></div>

Solution 2:

Based on Doug's hint about comparing offsetWidths, here's a working solution I came up with. Elements with the vscroll class are styled overflow-y: scroll;.

$(document).ready(function () {
    var scrollables = document.getElementsByClassName('vscroll');
    if( scrollables.length && 0 === scrollables[0].offsetWidth - scrollables[0].clientWidth ) {
        for ( const scrollable of scrollables ) {
            scrollable.style.background = 'url("/images/updnarrows_75.png") no-repeat 60% 50%';
        }
    }
});

The image is a set of faded up/down arrows that appear centered in the background of the div.

Post a Comment for "Detect If Scrollbar Is Visible (e.g. On A Mobile Device)"