Stevers
Stevers

Reputation: 535

jQuery toggle class with delay works only once

I am clearly missing something fundamental when it comes to jQuery, anonymous functions, and delays.

The following code works only ONCE per page load (it will add the class, then remove it after 1 second, and if i click again, it will add the class, but will NEVER remove the class for the duration of the page, unless I reload the page):

var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(){
$(this).removeClass("highlight");
});

HOWEVER,

if I add the (non-existant) function call as a parameter, AND I call it in my anonymous function, then the add/remove class combination will work indefinitely.

var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(randomFunction){
$(this).removeClass("highlight");
randomFunction(); //this makes it seemingly 'miraculously' work??
});

Side Note:

var jElement = $(currElem);
jElement.addClass("highlight")
.delay(1000)
.queue(function(randomFunction){
$(this).removeClass("highlight");
// this does NOT work; if I dont actually call the 'randomFunction'
// so that function, even though it does nothing; must somehow cause 
// the implicit call of 'dequeue()' ??
});

Upvotes: 3

Views: 2273

Answers (2)

Alexander
Alexander

Reputation: 23537

There is no miracle there. This behavior it's written in the documentation of .queue().

Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.

$('#foo').slideUp().queue(function() {
  alert('Animation complete.');
  $(this).dequeue();
});

As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:

$("#test").queue(function(next) {
    // Do some stuff...
    next();
});

Upvotes: 5

Kevin B
Kevin B

Reputation: 95061

the randomFunction is actually referred to as next and references the .dequeue method. Calling it causes the queue to continue on to the next item in the queue.

http://api.jquery.com/queue/

Upvotes: 2

Related Questions