How to Reverse JQuery Animation

I'm very new to JQuery and web dev in general and I need some help. I have been googling this for a couple days now and I can't seem to find a solution that works. I have seen the same question asked on here a lot but many of the answers have been earmarked as outdated in the current release of JQuery.

Basically I have a 'div' that I want to be focused in the middle of the screen when it is clicked. This part works fine. What I can't figure out how to do is have the same 'div' go back to its original position when clicked a 2nd time.

$(document).on("page:change", function() {
  $("#profile").on ("click", function() {
    $("#profile").animate({right: '15%', height: '+=50px', width: '+=25%'});
    $("#profile").css("position", "absolute"); // So that the div can maintain its normal position in bootstrap grid up until animation
    $("#fadeback").css("opacity", 0.6).fadeIn(300); // Fades everything else on page
  });
});

So, I mostly just need a way to 'undo' this set of operations upon a 2nd click. If you have another idea completely separate from my current implementation I'm completely open to it. Thanks for the help!!!

Answers 1

  • Try this:

    function firstClick() {
        alert('put your animation');
        $(this).one("click", secondClick);
    }
    function secondClick() {
        alert('put your reverse animation');
        $(this).one("click", firstClick);
    }
    
    $("#profile").one("click", firstClick);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="profile">
    click me
    </div>

    with your code:

    function firstClick() {
       $("#profile").animate({right: '15%', height: '+=50px', width: '+=25%'});
        $("#profile").css("position", "absolute"); // So that the div can maintain its normal position in bootstrap grid up until animation
        $("#fadeback").css("opacity", 0.6).fadeIn(300); // Fades everything else on page
      });
    }
    function secondClick() {
    // reverse your animation
    }
    
    
    $(document).on("page:change", function() {
    $("#profile").one("click", firstClick);
    });
    

Related Articles