Open In App

How to change the color of any div that is animated using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn to change the color of any HTML div that is animated using jQuery.We will be using the jQuery .animate() method to change the background colors of any element. 

The jQuery .animate() method is used to create smooth animations by changing the CSS properties of elements over time. It allows you to specify the duration, easing, and target values, providing dynamic and visually appealing effects to elements on a web page.

Syntax:

(selector).animate({css styles},speed,easing,callback)

CSS styles define CSS properties, such as background color, padding, margin, etc. Speed specifies the speed of the animation which is by default  400 milliseconds. The option easing specifies the speed of the element in different points of the animation, for example, swing or linear. The callback is a function to be executed after the animation completes.

Example: The following example helps to change the color of any div that is animated.

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
    <script src=
    </script>
    <style>
        div {
            width: 300px;
            border: solid 1px black;
            border-radius: 5px;
            margin-left: 20px;
        }
    </style>
</head>
 
<body>
    <h2 style="color: green">GeeksforGeeks</h2>
    <p>
        <input type="button" id="btn1" value="Animate" />
    </p>
    <div id="div">Animate Colors</div>
    <script>
        let animate = true;
        $("#btn1").click(function () {
 
            // Changing the background color alongwith
            // changing width of the div tag
            if (animate)
                $("#div").animate({
                    "background-color": "red",
                    width: "200px"
                }, 800);
            else
                $("#div").animate(
                    {
                        "background-color": "green",
                        width: "300px"
                    },
                    800
                );
 
            animate = !animate;
        });
    </script>
</body>
</html>


Output:



Last Updated : 05 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads