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 Sc
You can do some easy stuff like:
function customScroll(id) {
window.location.href = "#mydiv"+id;
}
Basically window.location.href
should help you.
This functionality can be achieved in some few steps.
First you get the position of the child using childElement.getBoundingClientRect();
which will return the following values
bottom : val
height: val
left: val
right: val
top: val
width: val
Then just position the child element according to the top left values into the parent element keeping child elements position
as absolute
. The parent Element's position
must be relative
type to place the child properly and get the effect of ScrollIntoView
.
childElement.style.position = 'absolute';
childElement.style.top = 'value in px';
childElement.style.left = 'value in px';
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. Heres 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.top <= parentRect.top + parentViewableArea.height);
// if you can't see the child try to scroll parent
if (!isViewable) {
// scroll by offset relative to parent
parent.scrollTop = (childRect.top + parent.scrollTop) - parentRect.top
}
}
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/