6

I have a certain question which goes into kind of debugging. I want you to ask, how I could find out which element of the whole markup is causing a scrollbar. Any kind of method would be fine. I thought about searching for overflow in developer tools, but this doesn't really help me.

Does anyone know how I could solve this?

supersize
  • 13,764
  • 18
  • 74
  • 133
  • show the page where it is happening – RST Jan 07 '15 at 15:17
  • 1
    @RST I don't have it live, and I guess that doesn't really matters for this question. Obviously I could search and find it after a long time, but I want it dynamically. – supersize Jan 07 '15 at 15:22
  • 1
    Possible duplicate: http://stackoverflow.com/questions/4880381/check-whether-html-element-has-scrollbars – hindmost Jan 07 '15 at 15:24
  • Iterate through all elements and check, if bounding rect bottom/right is greater than viewport (or any element which has scrollbar(s)) height/width. – Teemu Jan 07 '15 at 15:28

1 Answers1

4

You will want to check a few things. First, that an element has an overflow that would produce a scrollbar: overflow: scroll forces them and overflow: auto will display them if necessary. In the case that the overflows are auto, you can then check it's scroll height against it's actual height.

function isScroller(el) {
    var isScrollableWidth, isScollableHeight, elStyle;
    elStyle = window.getComputedStyle(el, null); // Note: IE9+
    if (elStyle.overflow === 'scroll' ||
        elStyle.overflowX === 'scroll' ||
        elStyle.overflowY === 'scroll') {
        return true;        
    }
    if (elStyle.overflow === 'auto' ||
        elStyle.overflowX === 'auto' ||
        elStyle.overflowY === 'auto') {
        if (el.scrollHeight > el.clientHeight) {
            return true;
        }
        if (el.scrollWidth > el.clientWidth) {
            return true;
        }
    }
    return false;
}

var els = document.querySelectorAll('body *');
for (var i = 0, el; el = els[i]; i++) {
    if (isScroller(el)) {
        console.log(el);
    }
}

You can see it here (open your console): http://jsfiddle.net/rgthree/zfyhby1j/

Note, that some touch devices may not produce an actual "scrollbar" except when scrolling. This won't detect that but, rather, that the element is capable of scrolling.

rgthree
  • 7,217
  • 17
  • 21