Last active
June 16, 2021 15:29
-
-
Save jaredcunha/2fe7e69c5495187ce4df254801ddef11 to your computer and use it in GitHub Desktop.
Accessible smooth scroll
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
document.querySelectorAll('a[href^="#"]').forEach(anchor => { | |
const anchorTargetId = anchor.getAttribute("href").replace("#", ""); | |
const anchorTarget = document.getElementById(anchorTargetId); | |
if (anchorTargetId.length) { // if statement gets around errors with href="#" | |
anchor.addEventListener('click', function (e) { | |
e.preventDefault(); | |
anchorTarget.setAttribute("tabindex", "-1"); | |
document.querySelector(this.getAttribute('href')).scrollIntoView({ | |
behavior: 'smooth' | |
}); | |
anchorTarget.focus(); | |
}); | |
anchorTarget.addEventListener('blur', function () { | |
anchorTarget.removeAttribute("tabindex"); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment