Total Page Preview:   000000000116

What is toggleClass() in jQuery?

jQuery toggleClass() 

In jQuery, the toggleClass() method is used to add or remove one or more classes from the selected elements. If a class is present, toggleClass() will remove it, and if it's not present, it will add it. This method simplifies the process of toggling classes on and off without explicitly checking for their presence.

Here's a small example to illustrate the use of toggleClass():
In this example:
  • The <style> section defines a CSS class named .highlight that changes the text color to red and makes the text bold.
  • The paragraph <p> element with the id "exampleParagraph" is initially styled without the .highlight class.
  • The button has an onclick attribute that triggers the toggleHighlight() JavaScript function.
  • Inside the toggleHighlight() function, $("#exampleParagraph").toggleClass("highlight"); is used to toggle the presence of the "highlight" class on the paragraph element.
Clicking the "Toggle Highlight" button will alternately add and remove the "highlight" class from the paragraph, changing its appearance based on the styles defined in the CSS.
 
 
 
 
 

 

Thank You

About Author

Brijesh Kumar

Database Developer

I have more then 6 years Experience in Microsoft Technologies - SQL Server Database, ETL Azure Cloud - Azure SQL Database, CosmosDB, Azure Data Factory, PowerBI, Web Job, Azure Function, Azure Storage, Web Apps, Powershall and Database Migration On-Premise to Azure Cloud.
LinkedIn : https://www.linkedin.com



Comments