Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between switchClass() and toggleClass() methods in jQuery?
The switchClass() method is used to switch classes from an element by replacing one class with another. It provides smooth animated transitions between classes. You need to add the jQuery UI library to your web page to use the switchClass() method, as it is not part of the core jQuery library.
The toggleClass() method is used to toggle between adding and removing classes from selected elements. If the class exists, it removes it; if it doesn't exist, it adds it. This method is part of the core jQuery library.
switchClass() Method
The switchClass() method smoothly transitions from one class to another with optional animation effects.
Example
You can try to run the following code to learn how to work with switchClass() ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").switchClass("blue", "red", 1000);
});
});
</script>
<style>
.blue {
background-color: blue;
width: 100px;
height: 100px;
}
.red {
background-color: red;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="blue"></div>
<button>Switch Class</button>
</body>
</html>
toggleClass() Method
The toggleClass() method adds or removes classes from the selected elements. If the class exists, it removes it; if it doesn't exist, it adds it.
Example
You can try to run the following code to learn how to toggle class ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, p").toggleClass("blue");
});
});
</script>
<style>
.blue {
color: blue;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p>This is demo text.</p>
<button>Toggle</button>
</body>
</html>
Key Differences
The main differences between switchClass() and toggleClass() are ?
Library Dependency: switchClass() requires jQuery UI library, while toggleClass() is part of core jQuery.
Functionality: switchClass() replaces one class with another, while toggleClass() adds or removes a single class.
Animation: switchClass() supports smooth animations between class transitions, while toggleClass() changes classes instantly.
Conclusion
Use switchClass() when you need animated transitions between two different classes, and toggleClass() when you want to simply add or remove a class from elements.
