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.
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.
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.
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.
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');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With