jmancherje jmancherje - 6 months ago 130
HTML Question

How to reverse a jQuery animation back to original CSS properties

There are a lot of very similar questions on here but I cannot find an exact answer to my question.

I am new to using the jQuery

.animate()
method and I want to know if there's a common or best method of reversing the animation?

Here is a fiddle for an example of what I've come up with:
Fiddle

Essentially all it does is use an if statement to check one CSS property and then animate it to one state or back to the other state.



$(document).ready(function () {
$("[name=toggle]").on("click", function () {
if ($('.box').width() < 125) {
$(".box").animate({
opacity: .3,
width: "125px",
height: "125px"
}, 250);
} else {
$(".box").animate({
opacity: 1,
width: "100px",
height: "100px"
}, 250)
}
});
});

.box {
background-color: lightblue;
box-shadow: 5px 5px 10px #000000;
width: 100px;
height: 100px;
display: block;
margin: 20px auto 0 auto;
border-radius: 25px;
}
[name="toggle"] {
display: block;
margin: 0 auto;
margin-top: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button name="toggle">Animate</button>
<div class="box"></div>





This is what I was able to come up with with my first exposure to .animate(), but I think there may be a better way.
Say you want to have an animation on hover, and reverse the animation when the mouse is moved off the element. Is there a way to easily reverse the jQuery animation easily? I am away I could use a :hover state with CSS, but this is a hypothetical question regarding jQuery .animate().

Answer

You can do that with plain CSS using transitions.

.animate-me {
    background-color:red;
    width:50px;
    height:50px;
    position:absolute;
    top:0;
    left:150px;
    transition:left 2s, background-color 2s;
  
}  
.animate-me:hover{
  left:0;
  background-color:blue;
}
<div class="animate-me"></div>

Usually css is simpler. However when browsers are old jquery might be your only way so I have included the JQuery way.

function animationForward(){
  $(".animate-me").animate(
  {
    opacity: 0.25,
    left: "100",
    height: "100"
  }, 5000, function() {
    animationBackward();
  }
)}
function animationBackward(){
  $(".animate-me").animate(
  {
    opacity: 1,
    left: "50",
    height: "50"
  }, 5000, function() {
    animationForward();
  }
)}
animationForward();
.animate-me {
  width:50px;
  height:50px;
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="animate-me"></div>

Comments