Javascript .scrollIntoView(boolean) provide only two alignment option.
What if I want to scroll the view such t
None of the solutions on this page work when an container other than the window/document is scrolled. The getBoundingClientRect approach fails with absolute positioned elements.
In that case we need to determine the scrollable parent first and scroll it instead of the window. Here is a solution that works in all current browser versions and should even work with IE8 and friends. The trick is to scroll the element to the top of the container, so that we know exactly where it is, and then subtract half of the screen's height.
function getScrollParent(element, includeHidden, documentObj) {
let style = getComputedStyle(element);
const excludeStaticParent = style.position === 'absolute';
const overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/;
if (style.position === 'fixed') {
return documentObj.body;
}
let parent = element.parentElement;
while (parent) {
style = getComputedStyle(parent);
if (excludeStaticParent && style.position === 'static') {
continue;
}
if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) {
return parent;
}
parent = parent.parentElement;
}
return documentObj.body;
}
function scrollIntoViewCentered(element, windowObj = window, documentObj = document) {
const parentElement = getScrollParent(element, false, documentObj);
const viewportHeight = windowObj.innerHeight || 0;
element.scrollIntoView(true);
parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;
// some browsers (like FireFox) sometimes bounce back after scrolling
// re-apply before the user notices.
window.setTimeout(() => {
element.scrollIntoView(true);
parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;
}, 0);
}