alyus
alyus

Reputation: 1007

Adding and removing a class with jQuery from your navigation

I have a simple navigation. I want to have a red border around the clicked nav item. For instance: If you click on Store, there should be a red border around the word Store. Then if you click on another nav item, Contact, the red border should come off the Store and on to the Contact item. Here's what I have so far.

HTML:

<ul class="nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">Store</a></li>
  <li><a href="#">Contact</a></li>
</ul>

CSS:

.active {
  border: 2px solid red;
  padding: 5px;
}

JS:

$('.nav li').click(function() {
   $(this).addClass('active');
   $(this).removeClass('active');
}

Not real strong in jQuery. Any help would be great... thanks!

Upvotes: 0

Views: 44

Answers (3)

Aaron
Aaron

Reputation: 1083

If your anchor tags take up the whole list item container space then you will need to do it this way:

$('.nav li a').click(function() {
    $('.nav li').removeClass('active');
    $(this).parent().addClass('active');
});

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39550

This code should be what you're looking for:

$('.nav li').click(function() {
   $('.nav li.active').removeClass('active');
   $(this).addClass('active');
}

Upvotes: 3

tymeJV
tymeJV

Reputation: 104795

Your JS is adding the class, then removing it instantly from the same element. Try this

$('.nav li').click(function() {
   $('.nav li').removeClass('active');
   $(this).addClass('active');
}

Upvotes: 3

Related Questions