views:

287

answers:

3

I have a toggle fade effect but when you click the button multiple times it fades in and out more than once. (So if i click the fade id 20 times fast it will fade in and out multiple times) How would I stop this and make it so that you can only toggle the fade when the animation was done? I tried getting the current value and making a if statement but it didn't work :*(

Thanks

jQuery.fn.fadeToggle = function(speed, easing, callback) {
  return this.animate({opacity: 'toggle'}, speed, easing, callback);  
};



$(document).ready(function() {
  $('.open').click(function() {
    $('#fadeMe').next().fadeToggle('slow');
  });
});
+2  A: 

You need to check if the element is not :animated, if so invoke the .animate:

  <body>
    <button class="open">open</button><br>
    <div id="fadeMe">fade me!</div>
    <style>#fadeMe { 
    width:20em;
    height:10em;
    background:black;
    color:#fff;
    }</style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"&gt;&lt;/script&gt;
    <script>
    jQuery.fn.fadeToggle = function(speed, easing, callback) {
      return this.animate({opacity: 'toggle'}, speed, easing, callback);  
    };



    $(document).ready(function() {
      $('.open').click(function() {
        var el = $('#fadeMe').next();
        if ( !el.is(':animated') ) {
            $(el).fadeToggle('slow');
        }
      });
    });
    </script>
    </body>

Demo: http://jsbin.com/irare

meder
updated solution.
meder
Sweet it works :)
PHPNooblet
This answers the question... but look at stop() answer below... that's what most people want in this situation.
ndp
Um - my original solution did incorporate stop, but I just thought of an alternative solution, that and I think I targeted the wrong elements in my original solution.
meder
A: 

This has been asked before, but hard to find it doing a search. What I ended up doing is taking a count of how many objects are being animated, and have the callback decrement the count until its zero, and run when its zero.

Frank Schwieterman
How would I do this?
PHPNooblet
I"m sorry I misunderstood the question. I thought you asked about the case where there are multiple concurrent animations, not multiple sequential animations.
Frank Schwieterman
+1  A: 

Use .stop(). This stops all animations on an element.

$('#fadeMe').next().stop().fadeToggle('slow');
recursive