1

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!

1 Answer 1

1

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');

   });
});
Sign up to request clarification or add additional context in comments.

3 Comments

This almost works perfectly! I'd like to comment out the e.preventDefault() as it breaks the link. The other problem is the <a> remains in hover state therefore, the a.active color doesn't show
@NabilKadimi what is it?
I'd add $(this).blur(); to remove the focus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.