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
The :active selector is used to select and style the active link. A link becomes active when you click on it. Tip: The :active selector can be used on all elements, not only links.
The active class is applied to the navigation element the user is currently viewing. In the case of your given code, the user is viewing the the profile. It will serve as a guide or reminder to where in the website the visitor is in.
It could be another style, such as #navlist a { color: #000; }
elsewhere is your code that is overriding 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 be overriding it.
NOTE: You say the actual jQuery is working as expected so I've focused purely on the CSS aspect of your question...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With