Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 27 Apr, 2021

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 syntax to use this method is as follows.

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>
      var 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :