Created
June 4, 2024 08:49
-
-
Save Jehu/1891a3736111d294ea737ba6b5a19aed to your computer and use it in GitHub Desktop.
Add CSS Class 'active' to navigation anker links
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
const updateActiveEl = (list) => { | |
if (!list) return; | |
var hash = window.location.hash; | |
if (!hash) { | |
let first = list.querySelector("a"); | |
if (first) { | |
first.classList.add("active"); | |
} | |
return; | |
} | |
list.querySelectorAll("a").forEach((el) => { | |
el.classList.remove("active"); | |
if (el.hash === hash) { | |
el.classList.add("active"); | |
} | |
}); | |
} | |
document.addEventListener("DOMContentLoaded", () => { | |
const list = document.querySelector("ul.my-navigation"); | |
updateActiveEl(list); | |
window.addEventListener("hashchange", () => { | |
updateActiveEl(list); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment