Reputation: 9512
Whe using jQuery .on('click', ...)
the function is executed twice:
$(document).ready(function () {
$('#collapsible-menu li a').click(function() {
$('#collapsible-menu li').removeClass('active');
$(this).parent('li').addClass('active');
});
});
So what happens is that the menu item goes active for an instant and then class goes away.
I have no clue why it's being fired twice. I don't want to use event.preventDefault()
or event.preventPropagation()
or return false
because then clicking the link will lead nowhere.
HTML:
<div class="collapse navbar-collapse" id="collapsible-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="/expenses">Expenses</a></li>
<li class=""><a href="/types">Types</a></li>
</ul>
</div>
Upvotes: 0
Views: 582
Reputation: 318182
You're clicking an anchor which redirects the page to /types
.
When you go to another page, whatever changes the javascript did, is lost.
So you're adding a class, then it redirects and the class is lost, the event handler doesn't fire twice
To avoid redirecting you can prevent the default action of the anchor
$('#collapsible-menu li a').click(function(e) {
e.preventDefault();
$('#collapsible-menu li').removeClass('active');
$(this).parent('li').addClass('active');
});
You can not expect to keep the class, and redirect at the same time, you have to do one or the other.
Upvotes: 2