Zennichimaro
Zennichimaro

Reputation: 5306

css add class to selected element

I'm using twitter bootstrap and to compose the header I have an like this one

  <ul class="nav navbar-nav">
    <li><a href="#" class="active" onclick="$(this).addClass('active')">Home</a></li>
    <li class="currentselection"><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>
  </ul>

The result looks like this:

Home | About | Contact

The LIVE version can be seen here:

Home | About | Contact - LIVE demo

The problem is, I'd like to style one and only one of the <a> that is active, so if the user clicked on About, the <a class="active">About</a> will be styled as active, while the <a>Home</a> will no longer be marked as active. This looks like very common and should be achieved easily, but I've been tinkering for 2 days and really have no idea and coming from C and CPP background, I'm very weak in javascript... would you please explain and mark which file (.css or .js or inside the .html itself) that I can achieve this?

Thank you very much for your help!

Upvotes: 1

Views: 2347

Answers (1)

Dustin
Dustin

Reputation: 846

You've tagged this with twitter-bootstrap, so does that mean that you have jQuery running? If so, then it's an easy fix.

You just setup the CSS like this:

.nav li a { color: #000; background: #FFF; }
.nav li a.active { color: #FFF; background: #FF0000 }

Then you can change the "active" class on the elements by putting a jQuery listener somewhere in your script. In this case, you're listening for someone to click on it:

$(function() {
   $('ul.nav li a').on('click', function(e) {

       //this line prevents the link for actually redirecting you
       e.preventDefault(); 

       //this line clears whatever the previous active link was
       $(this).closest('ul').find('li a.active').removeClass('active');

       //this line adds the class to the current link
       $(this).addClass('active');

   });
});

Upvotes: 1

Related Questions