I researched quite a bit on onClick changes for links but couldn't quite figure out the solution I need. I have a side bar menu that contains three links. I have a default "active" class added to the content I want to appear as default. However when I click another link in the sidebar, I want the previous link's "active" class to be removed, replaced with "inactive", then apply "active" to the new link. Here's my code:
HTML:
<div id="sidebar">
<ul>
<li><a href="#" id="1" class="active">1</a></li>
<li><a href="#" id="2" class="inactive">2</a></li>
<li><a href="#" id="3" class="inactive">3</a></li>
</ul>
</div>
CSS:
a.active {
background-color:#ccd9ff;
border-radius:15px 15px;
}
a.inactive {
border:0;
background:0;
}
jQuery:
$(function(){
$('a.inactive').click(function(){
$('a.inactive').removeClass('inactive');
$(this).addClass('active');
});
});
I read this previous post which helped me figure out how to addClass onclick (above), however I wasn't able to then remove the 'active' class of the inactive links. Can someone help me out?
Try this:
You need to only remove the class from the current
a
.If I"m understanding, you want this:
Event delegation would be nice here. You can use the
delegate()
[docs] method to only trigger the handler on descendants of#sidebar
that have theinactive
class.Then use the
toggleClass()
[docs] method to toggle theactive
andinactive
classes.You can test the code here: http://jsfiddle.net/dstpt/