152

I was trying out jquery with this example:

 $(document).ready(function(){
      $("button").mouseover(function(){
        $("p#44.test").css("background-color","yellow");
        $("p#44.test").hide(1500);
        $("p#44.test").show(1500);
        $("p#44.test").css("background-color","red");
      });
    });

I expected the following to happen:

1. Color of <p> to turn yellow
2. <p> to slowly fade
3. <p> to slowly show
4. Color of <p> to turn red

But this is what actually happened:

1. <p> turned red
2. <p> slowly hid away
3. <p> slowly showed

Why is that?

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242

3 Answers3

235

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

fureigh
  • 113
  • 2
  • 5
Klemen Slavič
  • 19,661
  • 3
  • 34
  • 43
23

try putting a delay on the last color fade.

$("p#44.test").delay(3000).css("background-color","red");

What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!

Community
  • 1
  • 1
austinbv
  • 9,297
  • 6
  • 50
  • 82
19

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

Peter Örneholm
  • 2,838
  • 20
  • 24
  • Setting the $p.css("background-color", "red"); before the $p.show will make it a little bit nicer, without that blink effect after showing the p-content again. – VKolev Nov 26 '10 at 07:57