views:

336

answers:

2
+2  Q: 

Toggle animation?

Hey,

I have this code:

$('.couch-hide').click(function() {
 $(this).animate({right:0},1000, 'easeOutBounce');   
});

I am trying to get it to toggle, so on first click, pop it out, then click again, and place it back inside. Would i need to set a variable as a tracker? To tell what stage it is at?

Thanks,

Ryan

+6  A: 

Just save the original value somewhere, and remember to stop any in-progress animation before starting a new one. The animation routines will take care of the rest:

var panel = $('.couch-hide');
var originalPos = panel.css("right");
panel.toggle(function() {
    $(this).stop().animate({right:0},1000, 'easeOutBounce');
  },
  function() {
    $(this).stop().animate({right:originalPos},1000, 'easeOutBounce');
  });
Shog9
+1 much better...
Paolo Bergantino
Thanks... untested though.
Shog9
I didnt know that toggle can work like that with anything. I will keep this in mind. This is VERY handy. Thanks for this. Why do you have the stop() in there?
Coughlin
@Coughlin: The call to stop() is there just make certain that I don't accidentally have two conflicting animations going at once (say, because you double-clicked the panel).
Shog9
A: 

generally jquery toggle works pretty much in a standard way as given below, however i have not really tried it with animation stuff but this may work.

$('.couch-hide').click(function() {
    $(this).animate({right:0},1000, 'easeOutBounce').toggle();

});

Vikram