Skip to content

Instantly share code, notes, and snippets.

@jakedohm
Created November 1, 2019 15:42
Show Gist options
  • Save jakedohm/e1836d6b269da50bc50a48ee4a4390c1 to your computer and use it in GitHub Desktop.
Save jakedohm/e1836d6b269da50bc50a48ee4a4390c1 to your computer and use it in GitHub Desktop.
/* Scroll to a certain pixel value from the top of the page */
function scrollToValue(pixel, offset = 200) {
const newWindowTop = pixel + offset
window.scroll({
top: newWindowTop,
behavior: 'smooth',
})
}
/* Scroll to an element on the page */
function scrollToElement($element) {
const elementOffset = $element.offsetTop
scrollToValue(elementOffset)
}
/* Handler for link callback */
function handleHashLinkClick(event) {
const $link = event.target
const hash = $link.hash
const $target = document.querySelector(hash)
if ($target) {
scrollToElement($target)
}
}
/* Attach handler to any link starting with a hash */
document.addEventListener('click', 'a[href*="#"]', handleHashLinkClick)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment