0

Codepen: http://codepen.io/Travo100/pen/DtwvG

I'm currently having an issue where I have a typical navigation menu setup and would like clicked on links to have a class added to them when clicked. However, I only want one link at a time to have this class on it. I've setup a codepen, and currently my code is making all the links posses this class, without removing it after the link is clicked on.

HTML

    <nav>
  <ul>
    <li><a href="#" class="selected">Home</a></li>
    <li><a href="#">About Us</a></li>
    <li><a href="#">Samples</a></li>
    <li><a href="#">Clients</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

CSS

a {
  text-decoration: none;
  padding: 10px;
  margin-left: 5px
}

li {
  float: left;
  list-style: none
}
.selected, a:hover {
  background-color: blue;
  color: white;
}

JS

 //When clicking on control list items 
$("nav a").click(function() {
//Deselect sibling elements 
$(this).siblings().removeClass( "selected" );
  //Select clicked element 
$(this).addClass( "selected" );
});  

I'm new is jQuery/javascript so I apologize for this basic question.

Thank you for your help.

1
  • please add the code to the question, instead of just a link Commented May 14, 2014 at 6:18

2 Answers 2

2

Use this, remove "selected" class from all nav a and add "selected" class to clicked element.

$("nav a").click(function() {
//Deselect sibling elements 
$("nav a").removeClass( "selected" );
  //Select clicked element 
$(this).addClass( "selected" );
});
Sign up to request clarification or add additional context in comments.

Comments

0

http://codepen.io/anon/pen/djxJH

Remove the class in general before adding it.

Code:

$("nav a").click(function() {
  $('.selected').removeClass( "selected" );
  $(this).addClass( "selected" );
});  

Comments

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.