Revert animation in second click

Asked

Viewed 79 times

1

I’m trying to reverse a simple animation when I press a button again. The first click animates a div removing its left margin, but when I press again I wanted to put the margin back in its normal value which is the 250px. For this purpose I decided to use jQuery’s toggle. The edge animation runs normally but the problem is that the div also disappears and reappears every time I press the button, which I suppose is the normal toggle behavior. My code is this::

$("#sidebar-toggle").click(function(){

$("#content").toggle(function(){

    $(this).animate({marginLeft:0},200);
},function(){

    $(this).animate({marginLeft:'250px'},200);
});

})

1 answer

1


This functionality of .toogle in switching two functions has already been removed since version 1.9. The method is used to animate hide/display elements.

I suggest you don’t use .animate for this: use .toggleClass() and animate via class in CSS using transition:

$("#sidebar-toggle").click(function(){
   $("#content").toggleClass("margem");
})
#content{
   width: 50px;
   height: 50px;
   background: red;
   margin-left: 250px;
   transition: margin-left 200ms;
}

#content.margem{
   margin-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></div>
<button id="sidebar-toggle">Clique</button>

  • Perfect :) thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.