Skip to content

Instantly share code, notes, and snippets.

@esamattis
Created August 24, 2022 21:59
Show Gist options
  • Save esamattis/6c2ed0dd06643242653be8e5b9790fe7 to your computer and use it in GitHub Desktop.
Save esamattis/6c2ed0dd06643242653be8e5b9790fe7 to your computer and use it in GitHub Desktop.
scrollIntoViewIfNeeded() that works with `overflow: scroll` parent divs etc. as well
function getScrollContainer(node: HTMLElement | null): HTMLElement | null {
if (!node) {
return null;
}
if (node.scrollHeight > node.clientHeight) {
if (node === document.body) {
return document.documentElement;
}
return node;
}
return getScrollContainer(node.parentElement);
}
function scrollIntoViewIfNeeded(el: HTMLElement, offsetSelector?: string) {
const scrollContainer = getScrollContainer(el);
let headerOffset = 0;
const margin = 30;
if (!scrollContainer) {
return;
}
if (offsetSelector) {
const header = scrollContainer.querySelector(offsetSelector);
if (header instanceof HTMLElement) {
headerOffset = header.clientHeight;
}
}
const rect = el.getBoundingClientRect();
if (rect.top < headerOffset) {
scrollContainer.scrollTo({
top: scrollContainer.scrollTop + rect.top - headerOffset - margin,
behavior: "smooth",
});
} else if (rect.bottom > scrollContainer.clientHeight) {
scrollContainer.scrollTo({
top:
scrollContainer.scrollTop +
rect.bottom -
scrollContainer.clientHeight +
margin,
behavior: "smooth",
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment