Search code examples
jqueryjquery-uianimationsequencing

Sequencing 2 lines of jQuery


I have the following lines of jQuery:

// When dragging ends
stop: function(event, ui) {
    // Replace the placeholder with the original
    $placeholder.after( $this.show() ).remove();
    // Run a custom stop function specitifed in the settings
    settings.stop.apply(this);
},

I don't want settings.stop.apply(this); to run UNTIL the line above is ($placeholder.after( $this.show() ).remove();), right now what's happening is the settings.stop is running to early.

With jQuery, how can I sequence these two lines to not proceed until the first is complete?


Solution

  • Animations happen asynchronously, which is why your $this.show() doesn't complete before the settings.stop.apply... line. All animations end up in the default ("fx") queue, which get played out one after the other. You can add something (even though its not an animation) to this sequence by using the queue function. So to adapt your example:

    // When dragging ends
    stop: function(event, ui) {
        // Replace the placeholder with the original
        $placeholder.after( $this.show() ).remove();
        // Run a custom stop function specitifed in the settings
        var x = this;   //make sure we're talking about the right "this"
        $this.queue(function() {
            settings.stop.apply(x);
            $(this).dequeue();    //ensure anything else in the queue keeps working
        });
    },
    

    Edit in response to your comment "What do you mean by the right "this"?":

    In JavaScript, this can be a tricky beast, that changes depending on the scope that it's referenced from. In the callback passed to the queue function, this will refer to the DOM object that the queue is being executed on (i.e. the DOM object referred to by $this. However, it's entirely possible that the this in the outer stop function is referring to some other object...

    Now, chances are, in your example, the outer this referred to the DOM object that is represented by the $this jQuery object (i.e. you've probably got a var $this = $(this); somewhere above where this snippet was taken from). In which case the x is unnecessary, since the two thiss would've been the same. But since I didn't know, I thought I should make sure. So, I created a closure* by creating a new variable, x, that referred to the "right" this (x is now caught in the closure, so we know for sure that it refers to the right thing inside the queue callback).

    * It's a bit of a slog, but if you make can it through that last linked article, you'll end up with a great understanding of how javascript hangs together.