Daniel Daniel - 7 months ago 14
Javascript Question

How to add an active class when a specific link has been clicked using bootstrap and jquery

I am trying to add a class to a clicked nav menu li using bootstrap and jquery.
When I click on a menu the class is added as expected, but not the related css property - in the specific case the colour red -
Below you can find a very simple example.



$(document).ready(function() {
$('#navlist a').click(function(e) {
e.preventDefault();
$('#navlist a').removeClass('active');
$(this).addClass('active');
});

});

.nav {
color: green;
}
.active {
color: red;
}

<ul class="list-unstyled" id="navlist">
<li id="home"><a class="nav" href="#">Home</a>
</li>
<li id="about"><a class="nav" href="#">About Us</a>
</li>
</ul>





fiddle

sid sid
Answer

Try this code -

$(document).ready(function(){
              $('#navlist a').click(function(e) {
              e.preventDefault();
              $('#navlist a').removeClass('active');
              $(this).toggleClass('nav');
              $(this).toggleClass('active');
          });
});

and this CSS -

a.nav:link { color: green; }
a.active:link { color: red; }

Here is fiddle - https://jsfiddle.net/yLpn2nmb/2/