How to Add Active Navigation Class Based on URL to Menu Item
Posted: February 18th, 2015 | Author: Julia | Filed under: Development, Tips and Tricks | Tags: active navigation class based on URL, add active class, javascript, jQuery | No Comments »When you work on a navigation menu for a website, it would be fine to make it the way the visitors on the website know on which page of the site they are on. This can be accomplished by adding an ‘active’ class to the menu item of the current page.
Javascript can access the current URL in parts.
To add an ‘active’ class to the navigation tab of any current page (when page’s url is = link’s href attribute), say, for the code below:
-
<ul>
-
<li><a href="/">Home</a></li>
-
<li><a href="/about/">About</a></li>
-
</ul>
(i.e. to visually indicate it’s the active navigation)
you have to add (after including the jQuery library to your project):
-
jQuery(function($) {
-
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
-
$('ul a').each(function() {
-
if (this.href === path) {
-
$(this).addClass('active');
-
}
-
});
-
});
*The perfect solution is to output this ‘active’ class from the server side, for example, similar solution for MVC:
-
<div class="btn-group-vertical btn-block" role="group">
-
@foreach (var btn in Model.Buttons)
-
{
-
<button type="button" class="btn btn-default @(((@Request.Url.AbsolutePath.Split('?')[0].Split('/')[Request.Url.AbsolutePath.Split('/').Length – 1]) == btn.Action)? "active" : "")" name="command" value="@btn.Action,@btn.Controller">
-
@btn.Title
-
</button>
-
}
-
</div>
Standalone example: view Active Navigation Class Based on URL in action >>
Leave a Reply