I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it does not work as expected - the page only refreshes and the default "Home" item in the menu remains highlighted.
Menu
<ul class="nav navbar-nav">
<li class="active"><a href="index.php">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Fire & Water <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="water-damage-restoration.php">Water Damage</a></li>
<li><a href="fire-smoke-damage-restoration.php">Fire Damage</a></li>
<li><a href="storm-flooding-restoration.php">Storm Damage</a></li>
<li><a href="commercial-restoration-services.php">Commercial Restoration</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Mold <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="mold-remediation.php">Mold Remediation</a></li>
<li><a href="black-mold.php">What is Black Mold?</a></li>
<li><a href="mold-removal.php">Mold "Removal" vs Remediation</a></li>
<li><a href="commercial-mold-removal.php">Commercial Mold Remediation</a></li>
</ul>
</li>
</ul>
This is Working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(e){
e.preventDefault();
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
$("li").removeClass('active');
$('a[href="' + hrefs + '"]').parents('li').addClass('active');
});
});
This is not working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(){
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
localStorage.setItem('activeTab', hrefs);
var activeTab = localStorage.getItem('activeTab');
$("li").removeClass('active');
alert("activeTab : " + activeTab);
$('a[href="' + activeTab + '"]').parents('li').addClass('active');
});
});