Skip to content

Instantly share code, notes, and snippets.

@artemsites
Last active May 17, 2024 09:23
Show Gist options
  • Save artemsites/9eef4d076a1a673b51eed9ffcac37b94 to your computer and use it in GitHub Desktop.
Save artemsites/9eef4d076a1a673b51eed9ffcac37b94 to your computer and use it in GitHub Desktop.
/**
* Проскроллить к элементу (верху или низу элемента)
*
* @author https://t.me/artemsites
*/
export default function scrollTo(params) {
let { selector, element, position } = params
let el = null
if (element) {
el = element
} else if (selector) {
el = document.querySelector(selector)
}
if (el) {
if (position === "bottom") {
const viewportHeight = window.innerHeight || document.documentElement.clientHeight
const elRect = el.getBoundingClientRect()
const scrollPosition = elRect.top + window.scrollY - viewportHeight + elRect.height
window.scrollTo({
top: scrollPosition,
behavior: 'smooth'
})
} else {
// "top"
el?.scrollIntoView({behavior: "smooth"})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment