Search code examples
javascripthtmlcss

Find first scrollable parent


I have this situation in which I need to scroll an element into the viewport. The problem is that I don't know which element is scrollable. For example, in Portrait the body is scrollable and in Landscape its an other element (and there are more situation which change the scrollable element)

Now the question, given an element which needs to be scrolled into the viewport, what is the best way to find its first scrollable parent ?

I've setup a demo here. With the button you can toggle between two different situations

<div class="outer">
    <div class="inner">
        <div class="content"> 
            ...
            <span>Scroll me into view</span>
        </div>
    </div>
</div>

The body is scrollable or .outer

Any suggestions ?


Solution

  • Just check if the scrollbar is visible, if not look to the parent.

    function getScrollParent(node) {
      if (node == null) {
        return null;
      }
    
      if (node.scrollHeight > node.clientHeight) {
        return node;
      } else {
        return getScrollParent(node.parentNode);
      }
    }