Created
November 1, 2019 15:42
-
-
Save jakedohm/e1836d6b269da50bc50a48ee4a4390c1 to your computer and use it in GitHub Desktop.
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
/* 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