FatDog47
FatDog47

Reputation: 462

Prevent new events be triggered on an element until currently event function finishes in jQuery

Consider following:

$('#theElement').on('click',function(){

  $(this).animate(...);
  $(this).doThis(...);
  $(this).doThat(...);

  $('anotherElement').animate(...);
  $('anotherElement').doThis(...);
  $('anotherElement').doThat(...);

});

As you see, here is a simple delegate function for onClick event. Now how is possible to make during this function execution, no other event be triggered on "#theElement"?

I tried to use preventDefualt(), but it stops whole execution which means that animate(), doThis() etc will not run too.

Upvotes: 0

Views: 50

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

Set a Boolean flag on the element when the function starts.

$('#theElement').on('click',function(){
    $(this).data('flagname',true);
    // ...

Test for the flag in your other events.

if (!$(this).data('flagname')) {  // !(undefined) is true
   // run code
}

Clear the flag when your animations are complete.

var $this = $(this); // 'this' is locally scoped
$this.animate(/* ... */, function() { 
    $this.data('flagname',false);
});

Upvotes: 2

bobek
bobek

Reputation: 8022

You have to nest them like this:

$(".yourclass").animate({}, time, function(){
   $(".yoursecondclass").animate({}, time, function(){
   });
});

Upvotes: 0

Related Questions