Reputation: 319
I've been trying really hard to accomplish what I'm trying to accomplish, but I can't get it to work the way I want. I have a navigation menu with first-level menu items (duh) and second-level menu items. It looks like this:
<ul class="nav" id="side-menu">
<li>
<a href="/admin/">Dashboard</a>
</li>
<li>
<a href="/admin/pages/">Pages</a>
</li>
<li>
<a href="#">Users<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li>
<a href="/admin/users/">All users</a>
</li>
<li>
<a href="/admin/users/roles/">Roles</a>
</li>
</ul>
</li>
</ul>
I'm using the following jQuery function to add the active
class to active menu items:
function setActive() {
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
// Remove active class from A element if the page isn't the dashboard.
if (location.pathname !== '/admin/' && $('[href="/admin/"]').hasClass('active')) {
$('[href="/admin/"]').removeClass('active');
}
};
This works fine for all first-level menu items and for the second-level menu item All users
, but when I go to /admin/users/roles/
, it makes All users
and Roles
active. The same thing happens when I go to /admin/users/roles/add/
. I think this happens because the code makes all menu items active which look like the window.location
, but I don't know how to only make Roles
active when I go to /admin/users/roles/
and /admin/users/roles/add/
, etc.
I really hope someone can help me with this. If you can, I'll buy you a beer.
Upvotes: 0
Views: 3220
Reputation: 2372
try this..
var loc = window.location.pathname;
$('#side-menu').find('a').each(function() {
$(this).toggleClass('active', $(this).attr('href') == loc);
});
and ue full absolute path in href i.e.http://yourdomain.com//admin/users/roles/
Upvotes: 1