How to add active class when specific link was clicked using bootstrap and jquery

I am trying to add a class to the li navigation menu using bootstrap and jquery. When I click on the menu, the class is added as expected, but the css property is not related - in the specific case, the color is 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

+5
source share
3 answers

Try this code -

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

and this CSS is

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

Here is the fiddle - https://jsfiddle.net/yLpn2nmb/3/

+1
source

It may be a different style, for example #navlist a { color: #000; } #navlist a { color: #000; } elsewhere, this is your code that overrides your .active class:

Try changing:

 .active { color: red; } 

To:

 #navlist a.active { color: red; } 

Or:

 #navlist a.nav.active { color: red; } 

This will increase the specificity of the class, which should override any other class that could override it.

NOTE. You say that actual jQuery works as expected, so I focus solely on the CSS aspect of your question ...

+3
source

Try something like this

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

I think this is what you want to do.

0
source

Source: https://habr.com/ru/post/1247688/


All Articles