jquerycssjquery-chaining

jQuery chaining css background-color, only works once


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"); }
);
});

Solution

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