Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Add active class and remove active from other element on click

Tags:

I'm new to jQuery, so I'm sorry if this is a silly question. But I've been looking through Stack Overflow and I can find things that half work, I just can't get it to fully work.

I have 2 tabs - 1 is active, the other is not. Once the inactive tab is clicked, I want that to be given the class of active, and the previous active class to be removed. And vice versa each time an inactive tab is clicked.

Any help would be great!

Here's what I currently have: http://jsfiddle.net/zLpe5/

Here's what I've tried for adding and removing the class:

$(document).ready(function() {
$(".tab").click(function () {
    $(".tab").removeClass("active");
    $(".tab").addClass("active");        
});
});

If anybody could help with with merging the 2 bits of script in my fiddle that'd be a massive help too. As I'm quite confused about how that's done!

Thank you :)

like image 910
Nick Avatar asked Mar 20 '14 09:03

Nick


1 Answers

Try this

$(document).ready(function() {
$(".tab").click(function () {
    $(".tab").removeClass("active");
    // $(".tab").addClass("active"); // instead of this do the below 
    $(this).addClass("active");   
});
});

when you are using $(".tab").addClass("active");, it targets all the elements with class name .tab. Instead when you use this it looks for the element which has an event, in your case the element which is clicked.

Hope this helps you.

like image 168
James Avatar answered Sep 24 '22 21:09

James