Daniel
Daniel

Reputation: 79

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

Upvotes: 5

Views: 669

Answers (3)

sid
sid

Reputation: 157

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 -

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

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

Upvotes: 1

David Wilkinson
David Wilkinson

Reputation: 5118

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

Upvotes: 3

Jamie Eltringham
Jamie Eltringham

Reputation: 806

Try something like this

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

});

I think that is what you want to happen

Upvotes: 0

Related Questions