Tommy D
Tommy D

Reputation: 418

Clear jQuery click queue

I have the function:

$(function(){
  $("#mydiv").click(function(){
if ($(this).hasClass('positive')) {
    $(this).delay(400).animate({right:'-210px'},1000)
          .addClass('negative').removeClass('positive')
} else {
    $(this).delay(400).animate({right:'10px'},1000)
          .addClass('positive').removeClass('negative')  
}
 }).clearQueue()
});

But if I click on my div a thousand times, it will execute the animation a thousand times. I tried to shop around on Jquery API documentation but nither .clearQueue() (as in the function) nor .stop(true) seems to be working.

Upvotes: 0

Views: 102

Answers (2)

Phylogenesis
Phylogenesis

Reputation: 7880

Make sure you use stop(true) before the delay() call. The following should do what you want:

$('#mydiv').click(function () {
    if ($(this).hasClass('positive')) {
        $(this)
            .addClass('negative')
            .removeClass('positive')
            .stop(true)
            .delay(400)
            .animate({ right: '-210px' }, 1000);
    } else {
        $(this)
            .addClass('positive')
            .removeClass('negative')
            .stop(true)
            .delay(400)
            .animate({ right: '10px' }, 1000);
    }
});

Example jsFiddle.

Upvotes: 1

szinter
szinter

Reputation: 303

You should unbind your element on the start of your handler. And when the animation is ready bind the handler again.

$(function(){
   $("#mydiv")click(function stg(e){
       var elem=$(e.target);
       elem.off('click',stg);
       if ($(this).hasClass('positive')) {
           $(this).delay(400)
                  .animate(
                    {right:'-210px'
                    ,complete:function(){elem.on('click',stg)}
                   },1000)
                  .addClass('negative').removeClass('positive')
       } else {
           $(this).delay(400)
                  .animate(
                    {right:'10px'
                    ,complete:function(){elem.on('click',stg)}
                    },1000)
                 .addClass('positive').removeClass('negative')  
       }
  })
}); 

The complete callback is only needed if you want to animate the element again after the animation.

Upvotes: 2

Related Questions