Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one active div allowed using jQuery

Tags:

jquery

Let's say I have 3 divs each with class item and only one can have class active at a time. For example:

<div class="item active">1</div>
<div class="item">2</div>
<div class="item">3</div>

I have a jQuery binding code that activates a div on the click event:

$(document).ready(function () {
    $('.item').bind('click', function() {
        addClass('active');        
        // now I need to remove active class from the previous selected item
    });
});

What is the best way of doing the housekeeping where I would remove the active class from any other div that may be active?

Thanks in advance.

like image 439
Allen Liu Avatar asked Sep 10 '11 09:09

Allen Liu


People also ask

How check class is active or not in jQuery?

Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.

How do I add a class active?

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.

How to use not function in jQuery?

The not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed. This method is often used to remove one or more elements from a group of selected elements.


1 Answers

you need to use $(this).addClass, not just on it's own, also, you can remove active class from all elements with active class before hand - like this:

$(document).ready(function () {
    $('.item').bind('click', function() {
        // remove the active class from all elements with active class
        $('.active').removeClass('active')
        // add active class to clicked element
        $(this).addClass('active');
    });
});
like image 200
Billy Moon Avatar answered Oct 04 '22 02:10

Billy Moon