BeNice
BeNice

Reputation: 2315

jQuery chaining order

Doing jQuery crash course all fine so far but:

        $(document).ready(function(){
            $("button").click(function(){
                $("#p1").css("color", "red")
                        .slideUp(2000)
                        .slideDown(2000);
            });
        });

<p id="p1">jQuery is fun!!</p>

This works fine but when I add a "change to blue" instruction (.css("color", "blue")) as the last link in the chain, the text turns blue as soon as I click the button instead of after the other events. What am I missing?

$("#p1").css("color", "red")
    .slideUp(2000)
    .slideDown(2000)
    .css("color", "blue");

Upvotes: 0

Views: 509

Answers (2)

joe_young
joe_young

Reputation: 4125

Try this:

$("#p1").css("color", "red")
    .slideUp(2000)
    .slideDown(2000, function() {       //function()" will add a callback
        $(this).css("color", "blue");   //this code will only execute after slideDown() has completed
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1">Hello</p>

This uses a callback, so that #p1 only turns blue after the animation has completed

Upvotes: 1

haim770
haim770

Reputation: 49115

Chaining itself doesn't guarantee order of execution, it only returns the previous jQuery context so that you'll be able to further work with it in a fluent way.

In your specific case, the invocation of slideUp and slideDown functions takes time to complete (because of their animated nature), but jQuery will not wait for them to finish before calling further (chained) methods.

You need to pass a callback instead:

$("#p1")
    .css("color", "red")
    .slideUp(2000, function() {
        $(this).slideDown(2000, function() {
            $(this).css("color", "blue");
        });
    });

See Fiddle

Upvotes: 1

Related Questions