27 Jan jQuery – Toggle CSS Class
To add or remove a class at the click of a button i.e., toggle, use the toggleClass() method in jQuery. Before moving further, we’ve prepared a video tutorial to toggle a class using jQuery:
Example
Let us see an example wherein we add a class and set the CSS properties for background color and font color for <h1>, <h2>, and <h3> elements with the click of a button. The same button clicked again will remove the CSS we set before i.e. the class will be removed:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, h3").toggleClass("demo");
});
});
</script>
<style>
.demo {
background: blue;
color: white;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p>This is demo text</p>
<h2>Heading 2</h2>
<p>This is another demo text.</p>
<h3>Heading 3</h3>
<p>This is yet another demo text.</p>
<button>Add/ Remove a class (TOGGLE)</button>
</body>
</html>
Output

No Comments