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"); }
);
});
edj
  • 523
  • 7
  • 17

1 Answers1

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");
    });
});
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
  • 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. – edj Apr 18 '17 at 17:52
  • 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 (http://stackoverflow.com/questions/5161988/in-jquery-how-to-use-multiple-delay-methods-with-css) 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. – edj Apr 18 '17 at 17:58
  • Still curious, though... Why did queue work the first time, but fail the second time? – edj Apr 18 '17 at 18:01
  • Ahhh! That was very enlightening. Thanks! – edj Apr 20 '17 at 16:43