Reputation: 780
I want to change the Active class in my navbar (using bootstrap), when I click on the link.
This is my html:
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="#">Phonebook</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
</div>
</div>
I've tried the follwing jQuery code that I got from an answer here in the site, but it doesn't work.
This is the code:
$(document).ready(function () {
$('.nav li a').click(function (e) {
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
debugger;
e.preventDefault();
});
});
Upvotes: 0
Views: 531
Reputation: 318162
You're complicating it :
$(document).ready(function () {
$('.nav li').on('click', function (e) {
$(this).addClass('active').siblings().removeClass('active');
});
});
and why would you add hash links to the anchors, and then use preventDefault in the event handler ?
Upvotes: 1