Reputation: 129
I'm looking to change the background color of the currently clicked on tab in my navigation menu. Then when I click a different tab, I want the old one to change back to the original background color. I've seen this tons of places, but every tutorial I follow hasn't worked for me.
Here is the html code I have for the navigation. Basically, I want to change the class "member_nav" to "member_nav_clicked" and then back to "member_nav" when a different tab is clicked.
<div class="member_nav">
<a href="javascript:;" onclick="javascript:nav1(); load_video('6')">Nav 1</a>
</div>
<div class="member_nav">
<a href="javascript:;" onclick="javascript:nav2(); load_video('2')">Nav 2</a>
</div>
<div class="member_nav">
<a href="javascript:;" onclick="javascript:nav3(); load_video('4')">Nav 3</a>
</div>
<div class="member_nav">
<a href="javascript:;" onclick="javascript:nav4(); load_video('5')">nav 4</a>
</div>
<div class="member_nav">
<a href="javascript:;" onclick="javascript:nav5(); load_video('3')">Nav 5</a>
</div>
I'm not going to include any of the javascript functions I've tried, since none of it was working.
Upvotes: 0
Views: 50
Reputation: 3783
Add an active
class, then on a click event find the currently active element and remove the active
class with $('.active').removeClass('active')
after this set the active
class to the clicked element $(this).addClass('active')
.
@adeneo's anwser in the comments is actually better.
$(this).addClass('active').siblings().removeClass('active');
Upvotes: 2
Reputation: 760
To be honest, this is some jQuery 101... i suggest you read up on the basics. I set up a jsFiddle for you, and i hope you wont just copy paste it but also try to learn something from it.
You can find it here: http://jsfiddle.net/wUpYh/1/
The code:
$('a').on('click', function(){
$('.member_nav_clicked').removeClass('member_nav_clicked').addClass('member_nav');
$(this).closest('.member_nav').removeClass('member_nav').addClass('member_nav_clicked');
});
So what happens is, i remove the member_nav class and add the clicked class. The line above it will take care of the previous clicked item. When an element has the active class, it will be removed before asigning it to the new clicked element.
But to be honest, a nicer way of doing this, would be to assign an active class and leave the normal class as it is. Like this:
$('a').on('click', function(){
$('.member_nav_clicked').removeClass('member_nav_clicked');
$(this).closest('.member_nav').addClass('member_nav_clicked');
});
Upvotes: 0