Categories
JavaScript Answers

How to add animate with jQuery toggleClass?

Spread the love

You can use jQuery’s toggleClass() method in combination with CSS transitions to animate the changes when toggling a class.

To do this, we can write

HTML:

<div id="myElement">Element to toggle</div>
<button id="toggleButton">Toggle Class</button>

CSS:

#myElement {
    width: 200px;
    height: 200px;
    background-color: red;
    transition: width 0.5s, height 0.5s;
}

#myElement.big {
    width: 400px;
    height: 400px;
}

JavaScript (jQuery):

$(document).ready(function() {
    $('#toggleButton').click(function() {
        $('#myElement').toggleClass('big');
    });
});

In this example, we have an HTML element (<div id="myElement">) that we want to toggle the class on.

When the button (<button id="toggleButton">Toggle Class</button>) is clicked, we toggle the class big on the myElement.

The CSS transitions are applied to the myElement, so changes to its width and height properties will be animated over a duration of 0.5 seconds when the class is toggled.

This setup provides a smooth animation effect when toggling the class using jQuery’s toggleClass() method.

You can adjust the CSS transition properties to control the animation speed and timing function to achieve the desired effect.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *