Menu Active Page
andysaktia
Posted on November 3, 2021
When I used scrollspy from bootstrap I realized it only applies to the case within a single page. The following idea came up to make the menu active with a check system from the url.
Container HTML
In my case the nav
menu container is like the following.
<div class="classynav">
<ul id="nav">
<li class="nav-item">
<a href="https://example.org/about.php">Tentang</a>
</li>
<li class="nav-item active">
<a href="https://example.org/project.php">Project</a>
</li>
</ul>
</div>
Script
The principle of this script handle only matches the selected url with the url in the container. For sub menu handlers, I haven't been able to find a meaningful solution, maybe you can use the split
attribute ?id
for the php web case, or maybe you have an interesting idea, please share it in the comments.
$(function(){
var url = window.location.href;
$(".classynav a").each(function() {
var d = $(this).attr('href');
if(url == d) {
$(this).closest(".nav-item").addClass("active");
}
});
});
Done
💖 💪 🙅 🚩
andysaktia
Posted on November 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript I Create a GitHub Searcher With JavaScript || GitHub API || JS API || JavaScript Tutorials
February 13, 2022