Cover Image for jQuery toggleClass() method
77 views

jQuery toggleClass() method

The jQuery toggleClass() method is used to toggle the presence of one or more CSS classes on the selected elements. It allows you to add a class if it is not present or remove it if it is already present. Essentially, it provides a way to easily switch between adding and removing a class.

The syntax for using the toggleClass() method is as follows:

$(selector).toggleClass(className);
  • selector: It is a string that specifies the elements to be selected.
  • className: It is a string or space-separated list of classes that you want to toggle on the selected elements.

Here’s an example of how you can use the toggleClass() method:

HTML:

<button id="myButton">Toggle Class</button>
<div id="myDiv" class="box">This is a div element.</div>

CSS:

.box {
  width: 100px;
  height: 100px;
  background-color: red;
}

.highlight {
  border: 2px solid blue;
}

JavaScript:

// Toggle the "highlight" class on the div element when the button is clicked
$('#myButton').click(function() {
  $('#myDiv').toggleClass('highlight');
});

In the above example, when the button with the ID “myButton” is clicked, the toggleClass() method is used to add or remove the “highlight” class on the div element with the ID “myDiv.” If the class is not present, it will be added, and if it is already present, it will be removed.

This will cause the div to toggle between having a blue border (when the “highlight” class is added) and having no border (when the “highlight” class is removed).

The toggleClass() method can also be used with multiple classes at once by passing a space-separated list of class names:

// Toggle multiple classes on an element
$('#myElement').toggleClass('class1 class2 class3');

The toggleClass() method provides an easy way to implement dynamic interactions, such as toggling the visibility or appearance of elements, based on user actions or other events. It is commonly used in combination with event handlers or other conditional logic to create interactive user interfaces.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS