Skip to content

Instantly share code, notes, and snippets.

@relyky
Created September 17, 2021 01:26
Show Gist options
  • Save relyky/1d663efa22e8ce2f8be793026354509a to your computer and use it in GitHub Desktop.
Save relyky/1d663efa22e8ce2f8be793026354509a to your computer and use it in GitHub Desktop.
JavaScript, window.scrollTo, offset
function scrollToOffset(element, offset /* int */)
{
//ref→https://newbedev.com/javascript-scrollintoview-smooth-scroll-and-offset
const bodyRect = document.body.getBoundingClientRect().top;
const elementRect = element.getBoundingClientRect().top;
const elementPosition = elementRect - bodyRect;
const offsetPosition = elementPosition - offset;
window.scrollTo({
top: offsetPosition,
behavior: "smooth"
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment