Skip to content

Instantly share code, notes, and snippets.

@md-riaz
Last active September 1, 2020 07:59
Show Gist options
  • Save md-riaz/76af1fca4d075bfa28cd329f72de4b72 to your computer and use it in GitHub Desktop.
Save md-riaz/76af1fca4d075bfa28cd329f72de4b72 to your computer and use it in GitHub Desktop.
Add Active Navigation Class Based on URL
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/clients/">Clients</a></li>
<li><a href="/contact/">Contact Us</a></li>
</ul>
</nav>
<script>
// menu active class add
if(location.pathname === "/"){
$("nav a[href='/']").addClass("active");
}
else{
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass("active");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment