Skip to content

Instantly share code, notes, and snippets.

@jaredcunha
Last active June 16, 2021 15:29
Show Gist options
  • Save jaredcunha/2fe7e69c5495187ce4df254801ddef11 to your computer and use it in GitHub Desktop.
Save jaredcunha/2fe7e69c5495187ce4df254801ddef11 to your computer and use it in GitHub Desktop.
Accessible smooth scroll
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