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?
Animations happen asynchronously, which is why your
$this.show()doesn’t complete before thesettings.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 thequeuefunction. So to adapt your example:Edit in response to your comment “What do you mean by the right “this”?“:
In JavaScript,
thiscan be a tricky beast, that changes depending on the scope that it’s referenced from. In the callback passed to thequeuefunction,thiswill refer to the DOM object that thequeueis being executed on (i.e. the DOM object referred to by$this. However, it’s entirely possible that thethisin the outerstopfunction is referring to some other object…Now, chances are, in your example, the outer
thisreferred to the DOM object that is represented by the$thisjQuery object (i.e. you’ve probably got avar $this = $(this);somewhere above where this snippet was taken from). In which case thexis unnecessary, since the twothiss 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(xis now caught in the closure, so we know for sure that it refers to the right thing inside thequeuecallback).* 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.