I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page. The line is split down the middle with regards of whether to do this client vs server side.
Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.
I have the following jQuery code to assign the "active" class to the <li> item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:
(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1
$(function () {
var str = location.href.toLowerCase();
$('#nav ul li a').each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$(this).parent().attr("class","active"); //hightlight parent tab
}
});
Is there a better way of doing this, guys? Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method? like instead of just the base URL it would be localhost/home/dashboard
so that it wouldn't be a substring of every link?
Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.
Here is my solution of this issue.
I created following extension method of HtmlHelpers class:
Then I have my menublock. It looks like this:
So my method returns class name to every div according to current action of Home controller. You can go deeper and add to the method one parameter, which specifies the name of the controller to avoid problems, when you have actions with the same name but of different controllers.
A custom HTML helper usually does the job fine:
and in your master page:
Now all that's left is define the .current CSS class.
What I usually do is assign a class to the body tag that's based on the path parts. So like, if you do a String.Replace on the path to turn /blogs/posts/1 to class="blogs posts 1".
Then, you can assign CSS rules to handle that. For example, if you have a menu item for "blogs", you can just do a rule like
or if you want a particular style if your on a post only vice if you're on the blog root page
Added support for areas:
Through JQuery u can do like this:
Original: http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item