Skip to content

Instantly share code, notes, and snippets.

@drpeck
Last active July 23, 2023 07:07
Show Gist options
  • Save drpeck/ccb4581fdf3469d498611121ca651739 to your computer and use it in GitHub Desktop.
Save drpeck/ccb4581fdf3469d498611121ca651739 to your computer and use it in GitHub Desktop.
Select active class on top nav
( function() {
function highlightActiveNav() {
// Get the current page's path
const currentPath = window.location.pathname;
// Select all `a` tags within `.nav-item` elements
const navLinks = document.querySelectorAll('.nav-item a');
// Loop through each link to check for a match
navLinks.forEach(link => {
const linkPath = new URL(link.href).pathname; // Extract pathname from the full URL
// If the link's path matches the current page's path, add the `active` class
if (linkPath === currentPath) {
link.classList.add('active');
// Check if the link has a parent nav item
const parentNavItem = link.closest('.nav-item.has-children');
if (parentNavItem) {
// Find the direct child `a` of the `.nav-item` and set its `active` class
const parentLink = parentNavItem.querySelector('> a.nav-link');
if (parentLink) {
parentLink.classList.add('active');
}
}
} else {
link.classList.remove('active');
}
});
}
// Call the function on page load
window.addEventListener('DOMContentLoaded', highlightActiveNav);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment