jQuery ToggleClass()
The jQuery toggleClass()
method adds or removes one or more classes from the selected elements, depending on whether they already have the specified classes. It is useful for dynamically toggling styles or functionality.
Key Topics
Basic Usage of toggleClass()
The toggleClass()
method toggles the specified class on the selected elements.
$("#box").toggleClass("highlight");
Explanation: This code toggles the highlight
class on the element with the ID box
. If the class is present, it is removed; otherwise, it is added.
Conditional Toggling
You can pass a boolean value to toggleClass()
to explicitly add or remove a class.
$("#box").toggleClass("active", true); // Adds the 'active' class
$("#box").toggleClass("active", false); // Removes the 'active' class
Explanation: The second argument specifies whether to add (true
) or remove (false
) the class explicitly, regardless of its current state.
Example: Using toggleClass()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery ToggleClass Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
</head>
<body>
<div id="box" style="width: 200px; height: 100px; background-color: gray; color: white; text-align: center; line-height: 100px;">
Toggle Me
</div>
<button id="toggleButton">Toggle Highlight</button>
<script>
$(document).ready(function() {
$("#toggleButton").click(function() {
$("#box").toggleClass("highlight");
});
});
</script>
</body>
</html>
Explanation: This example demonstrates how to toggle the highlight
class on a box element when a button is clicked. The class changes the background color and text color dynamically.
Key Takeaways
- Dynamic Styling: Use
toggleClass()
to add or remove classes dynamically for interactive styling. - Boolean Control: Pass a boolean value to control the class addition or removal explicitly.
- Efficient Interaction: Ideal for creating responsive and user-friendly interfaces that react to events.