DEV Community

Cover image for Menu Active Page
andysaktia
andysaktia

Posted on

Menu Active Page

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> 
Enter fullscreen mode Exit fullscreen mode

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"); } }); }); 
Enter fullscreen mode Exit fullscreen mode

Done

Top comments (0)