5

I am new to jQuery and I am trying a simple program. In this program what I am trying to achieve is that when I will click the div text then first line will fadeout then it will change background colour and then it will fade in so overall it will give effect of changing colour slowly, but what happening here is when I click the text the line changes colour suddenly then it fades out and then it fades in. So I was wondering if there is a way to make colour changing code execute after execution of fadeout.

my program:

        $(document).ready(function(){
            $("#firstDiv").click(function(){
                //                    $(this).fadeOut(1000);

                $(this).fadeOut(1000);

                $(this).css("background-color", "aqua");

                $(this).fadeIn(1000);


            });
        });
    </script>
</head>
<body>
    <div id="firstDiv" style="background-color: yellowgreen">
        Click Me
    </div>
</body>

Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110

3 Answers3

4

You have to put the color changing in a callback passed to fadeOut:

$(this).fadeOut(1000, function() {
    $(this).css("background-color", "aqua");
}).fadeIn(1000);

Everything you put in the callback is executed after fadeOut finished. fadeIn is not executed immediately because effect methods are queued automatically.

But: If you are doing something computational expensive (i.e. it takes time) in the callback and you want to call fadeIn only after this has finished, you have to put fadeIn in the callback too:

$(this).fadeOut(1000, function() {
    $(this)
      .css("background-color", "aqua")
      .fadeIn(1000);
});

Otherwise fadeIn will be called before the callback finished.


Also worth reading in this context: Can somebody explain jQuery queue?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
3

You can use the callback function of fadeOut() like this:

$(this).fadeOut(1000, function(){
    $(this).css("background-color", "aqua").fadeIn(1000);
});
Khoa Nguyen
  • 1,319
  • 7
  • 21
0

The jQuery queueing API might be worth a look, it's meant to let you queue up a sequence of actions that will be applied to the selected item.

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

GordonM
  • 31,179
  • 15
  • 87
  • 129