Created
August 24, 2022 21:59
-
-
Save esamattis/6c2ed0dd06643242653be8e5b9790fe7 to your computer and use it in GitHub Desktop.
scrollIntoViewIfNeeded() that works with `overflow: scroll` parent divs etc. as well
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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