Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain JavaScript - ScrollIntoView inside Div

I have the requirement to scroll a certain element inside a div (not a direct child) into view.


Basically I need the same functionality as ScrollIntoView provides, but for a specified parent (only this parent should scroll).
Additionally it is not possible for me to use any 3rd party libraries.


I am not quite sure on how to approach this problem, as I do very limited JavaScript development. Is there someone that could help me out?


I found this code that would do exactly what I need, but unfortunately it requires JQuery and I was not able to translate it to plain JavaScript.

like image 799
JDC Avatar asked Jul 31 '17 06:07

JDC


1 Answers

I think I have a start for you. When you think about this problem you think about getting the child div into the viewable area of the parent. One naive way is to use the child position on the page relative to the parent's position on the page. Then taking into account the scroll of the parent. Here's a possible implementation.

function scrollParentToChild(parent, child) {

  // Where is the parent on page
  var parentRect = parent.getBoundingClientRect();
  // What can you see?
  var parentViewableArea = {
    height: parent.clientHeight,
    width: parent.clientWidth
  };

  // Where is the child
  var childRect = child.getBoundingClientRect();
  // Is the child viewable?
  var isViewable = (childRect.top >= parentRect.top) && (childRect.bottom <= parentRect.top + parentViewableArea.height);

  // if you can't see the child try to scroll parent
  if (!isViewable) {
        // Should we scroll using top or bottom? Find the smaller ABS adjustment
        const scrollTop = childRect.top - parentRect.top;
        const scrollBot = childRect.bottom - parentRect.bottom;
        if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
            // we're near the top of the list
            parent.scrollTop += scrollTop;
        } else {
            // we're near the bottom of the list
            parent.scrollTop += scrollBot;
        }
  }

}

Just pass it the parent and the child node like this:

scrollParentToChild(parentElement, childElement)

Added a demo using this function on the main element and even nested elements

https://jsfiddle.net/nex1oa9a/1/

like image 101
Jordan Maduro Avatar answered Oct 14 '22 04:10

Jordan Maduro