Skip to content

Instantly share code, notes, and snippets.

@Jehu
Created June 4, 2024 08:49
Show Gist options
  • Save Jehu/1891a3736111d294ea737ba6b5a19aed to your computer and use it in GitHub Desktop.
Save Jehu/1891a3736111d294ea737ba6b5a19aed to your computer and use it in GitHub Desktop.
Add CSS Class 'active' to navigation anker links
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