Jquery animation switch div slowly with animation

Issue

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style type="text/css">
        .header {
            position: absolute;
            top: 0px;
            height: 50px;
            width: 100%;
            background: #f00;
        }
    </style>
</head>

<body>
    <ul>
        <li>
            <div class="header">
                <p>Header</p>
            </div>
        </li>
        <li>
            <div class="header">
                <p>Hello World</p>
            </div>
        </li>
        <li>
            <div class="header">
                <p>Footer</p>
            </div>
        </li>
    </ul>
    <script>
        $(".header").on("click", function () {
            var e = $(this).closest("li");
            
            
            e.prev().insertAfter(e);
        })
    </script>
</body>

</html>

I am trying to switch the li element with animation which will be like slowly moving upwards but can’t seem to make it, above is what I have practiced till now and I am weak at jquery animation hope to get your feedback/help what I want is animation like this code http://jsfiddle.net/BYossarian/GUsYQ/5/ any answer or help would be appreciated.

Solution

your CSS does not visible effect on this animation

var animating = false;
$(".header").on("click", function() {
     var clickedDiv = $(this).closest("li");
    if (animating) {
        return;
    }

    prevDiv = clickedDiv.prev(),
    distance = clickedDiv.outerHeight();

    if (prevDiv.length) {
        animating = true;
        $.when(clickedDiv.animate({
            top: -distance
        }, 600),
        prevDiv.animate({
            top: distance
        }, 600)).done(function () {
            prevDiv.css('top', '0px');
            clickedDiv.css('top', '0px');
            clickedDiv.insertBefore(prevDiv);
            animating = false;
        });
    }
});
li {
   width: 200px;
    border: 1px solid black;
    position: relative;
    margin:10px;
}
li .header {
    border: 1px solid black;
    position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>      
   <li>
       <div class="header"> 
         <p>Header</p> 
      </div>
      </li>
      <li>
      <div class="header"> 
         <p>Hello World</p> 
      </div> 
      </li>
      <li>
      <div class="header"> 
         <p>Footer</p> 
      </div>  
  </li>
</ul>

Answered By – Robin Hood

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.