0

I'm trying to chain background-color changes of a paragraph with jQuery. The following code works on the first click: change color to green, hide it, show it, then change color to yellow.

On the second click, the color changes to green, but nothing else happens. No further clicks do anything at all. What's wrong?

$( "#p1" ).click(function( event ) {
$("#p1").css("background-color","green").slideUp(2000).slideDown(2000).queue( 
function() { $("#p1").css("background-color", "yellow"); }
);
});

1 Answer 1

1

No need to use .queue here, this will do just fine:

$("#p1").click(function(event) {
  $("#p1").css("background-color", "green").slideUp(2000).slideDown(2000, function() {
    $("#p1").css("background-color", "yellow");
  });
});

Alternatively, use .clearQueue

$("#p1").click(function(event) {
  $("#p1").clearQueue().css("background-color", "green").slideUp(2000).slideDown(2000).queue(
    function() {
      $("#p1").css("background-color", "yellow");
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! The first solution (removing queue) fixed it. I'd read a different post that queue (or another delay strategy) was required because css changes are applied immediately.
As function calls like this are delayed by the actions preceding it, I wonder where I can see that documented. I haven't found it anywhere. This question (stackoverflow.com/questions/5161988/…) addresses a similar problem as mine, but doesn't mention using a function as a solution. Instead it states that setTimeout is the only way to do it.
Still curious, though... Why did queue work the first time, but fail the second time?
Ahhh! That was very enlightening. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.