I want to highlight the active page on the side bar menu using JavaScript. I am using INSPINIA theme.
I've tried using JavaScript and it's working fine for normal menus. But it's not working for submenus. I want to display in
class instead of active
class for submenus. Please check my code and help me.
HTML
<nav class="navbar-default navbar-static-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav metismenu" id="side-menu">
<li>
<a href="dashboard.html"><i class="fa fa-th-large"></i><span class="nav-label">Dashboards</span></a>
</li>
<li>
<a href="#"><i class="fa fa-building"></i><span class="nav-label">Company</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse">
<li><a href="addcompany.html">Add Company</a></li>
<li><a href="#">View Company</a></li>
</ul>
</li>
<li>
<a href="mailbox.html"><i class="fa fa-envelope"></i><span class="nav-label">Person</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse">
<li><a href="addperson.html">Add Person</a></li>
<li><a href="#">View Person</a></li>
</ul>
</li>
</ul>
</div>
</nav>
JavaScript
$(document).ready(function () {
var url = window.location;
// for sidebar menu but not for metismenu submenu
$('ul.metismenu a').filter(function () {
return this.href == url;
}).parent().siblings().removeClass('active').end().addClass('active');
// for metismenu which is like a submenu
$('ul.nav-second-level a').filter(function () {
return this.href == url;
}).parentsUntil(".metismenu > .nav-second-level").siblings().removeClass('active').end().addClass('active');
});
Expected output
<li class="active">
<a href="#"><i class="fa fa-building"></i><span class="nav-label">Company</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse in">
<li><a href="addcompany.html">Add Company</a></li>
<li><a href="#">View Company</a></li>
</ul>
</li>
Actual Output
<li class="active">
<a href="#"><i class="fa fa-building"></i><span class="nav-label">Company</span><span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse active">
<li><a href="addcompany.html">Add Company</a></li>
<li><a href="#">View Company</a></li>
</ul>
</li>
I found the answer.
$(function() {
setNavigation();
});
function setNavigation() {
var path = window.location.pathname;
path = path[0] == '/' ? path.substr(1) : path; //it will remove the dash in the URL
$("ul.metismenu a").each(function() {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
$("ul.metismenu .nav-second-level a").each(function() {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).parent().parent().closest('li').addClass('active');
$(this).closest('ul').addClass('in');
}
});
}