Open In App

How to animates div’s left property with a relative value using jQuery ?

In this article, we will learn how to animate a division element’s left property with a relative value using jQuery. This can be used in situations where a division element has to be animated using only one property.

Approach: We will be using the jQuery click() and animate() methods. 



Note: Remember to set the position as absolute of the division element since the left property can not be used on statically positioned elements.

Example: In this example, the division element is animated by clicking on the two buttons and the division element has an easing property of slow. The first button with a class of left-arrow decrements the left property by 25 pixels whereas the second button with a class of right-arrow increments the left property by 25 pixels.






<!DOCTYPE html>
<html>
  <head>
    <script src=
    </script>
  
    <!-- Basic inline styling -->
    <style>
      body {
        text-align: center;
      }
  
      h1 {
        color: green;
        font-size: 40px;
      }
  
      p {
        font-weight: bold;
        font-size: 25px;
      }
  
      /* Necessary for animation to work */
      .animate-div {
        position: absolute;
        background-color: green;
        left: 730px;
        width: 75px;
        height: 75px;
        margin-top: 2rem;
      }
  
      button {
        cursor: pointer;
        margin: 0 auto;
      }
    </style>
  </head>
  
  <body>
    <h1>GeeksforGeeks</h1>
    <p>
      jQuery - Animate a div's left 
      property with a relative value
    </p>
  
    <button class="left-arrow"><</button>
    <button class="right-arrow">></button>
    <div class="animate-div"></div>
    <script type="text/javascript">
      $(".left-arrow").click(function () {
        $(".animate-div").animate({ left: "-=25px" }, "slow");
      });
  
      $(".right-arrow").click(function () {
        $(".animate-div").animate({ left: "+=25px" }, "slow");
      });
    </script>
  </body>
</html>

Output:


Article Tags :