Created
October 21, 2018 02:44
-
-
Save BrandonClapp/8a120c22b39d6ce643527abb1e460faf to your computer and use it in GitHub Desktop.
This file contains hidden or 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 anchorLinkHandler(e) { | |
const distanceToTop = el => Math.floor(el.getBoundingClientRect().top); | |
e.preventDefault(); | |
const targetID = this.getAttribute("href"); | |
const targetAnchor = document.querySelector(targetID); | |
if (!targetAnchor) return; | |
const originalTop = distanceToTop(targetAnchor); | |
window.scrollBy({ top: originalTop, left: 0, behavior: "smooth" }); | |
const checkIfDone = setInterval(function() { | |
const atBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2; | |
if (distanceToTop(targetAnchor) === 0 || atBottom) { | |
targetAnchor.tabIndex = "-1"; | |
targetAnchor.focus(); | |
window.history.pushState("", "", targetID); | |
clearInterval(checkIfDone); | |
} | |
}, 100); | |
} | |
const linksToAnchors = document.querySelectorAll('a[href^="#"]'); | |
linksToAnchors.forEach(each => (each.onclick = anchorLinkHandler)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment