jQuery: How to Toggle Class Names
To toggle one or more classes with jQuery, use the toggleClass()
method. Let's create a button and a jQuery click function to toggle a class attribute on the same button.
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$(this).toggleClass('bar');
});
On the first click, the class "bar" is added and toggled on and off on each subsequent click.
Toggling Multiple Classes
To toggle multiple classes, add them inside toggleClass()
separating each one by a space.
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$(this).toggleClass('bar active highlight');
});
Always Add or Remove Classes
To always add or remove classes, pass a boolean value as the second argument of toggleClass()
:
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$(this).toggleClass('bar', true);
});
In the example above, the class "bar" can only be added and will never be removed.
Check Current Classes Before Adding or Remove a Class
To check what classes are currently on an element and do something if a class exists, pass a function as the first argument of toggleClass()
.
<button type="button" id="foo" class="bar">Click me</button>
$('#foo').click(function() {
$(this).toggleClass(function(index, currentClass) {
if (currentClass == 'bar') {
$(this).removeClass('bar').addClass('foo');
};
});
});
Conclusion
The toggleClass()
method is the easiest way to toggle adding or removing one or many classes with jQuery.