How to change active class while click to another link in bootstrap use jquery?
You are binding you click on the wrong element, you should bind it to the a
.
You are prevent default event to occur on the li
, but li
have no default behavior, a
does.
Try this:
$(document).ready(function () {
$('.nav li a').click(function(e) {
$('.nav li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
I am using bootstrap navigation
This did the job for me including active main dropdown's and the active children
$(document).ready(function () {
var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="' + url + '"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});