JQuery to switch delayed class only works once

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

The following code only works with ONCE on page load (it will add the class and then remove it after 1 second and if I click again it will add the class but NEVER remove the class throughout the page unless I reload the page):

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

      

HOWEVER

if I add a (not existing) function call as a parameter, AND I call it in my anonymous function, then the add / remove class combination will run 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()' ??
});

      

+3


source to share


2 answers


There is no miracle. This behavior was written in the documentation .queue()

.



Note that when adding a function with we have to ensure that it is called so that the next function on the line is executed. .queue()

.dequeue()

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

      

Since jQuery 1.4 , the called function passes another function as the first argument. When called, this will automatically deactivate the next item and move the queue. We use it like this:

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

      

+5


source


randomFunction

is actually called next

and refers to a method .dequeue

. The call invokes the queue to go to the next item in the queue.



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

+2


source







All Articles