- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
jQuery toggleClass() with Examples
The toggleClass() method in jQuery is used to toggle between adding or removing one or more classes from selected elements.
Syntax
The syntax is as follows −
$(selector).toggleClass(classname,func(index,currentclass),switch)
Above, class name specifies one or more class names to add or remove, whereas func is a function that returns one or more class names to add or remove.
Example
Let us now see an example to implement the jQuery toggleClass() method −
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").toggleClass("demo"); }); }); </script> <style> .demo { background-color: orange; color: white; border: 1px solid blue; } </style> </head> <body> <h2>Exam Info</h2> <p>Examination begins on 24th December. The students are requested to submit project report before 15th December.</p> <button>Toggle</button> </body> </html>
Output
This will produce the following output −
On clicking Toggle, the appearance of the above text will change −
On clicking Toggle again, the appearance gets back to the initial stage −
Advertisements