Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 289
Daniel Avatar asked Apr 22 '16 08:04

Daniel


People also ask

How do you make a link active when clicked?

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.

What does the active class in bootstrap do?

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.


1 Answers

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...

like image 75
David Wilkinson Avatar answered Sep 28 '22 03:09

David Wilkinson