jQuery Animation Triggered By User Interaction Depends on Previous
Animation Completion
I have a timeline that can be zoomed by clicking a zoom in or zoom out
button. This timeline doesn't all fit on the screen at once, so it is a
scrollable div. When the user clicks to zoom, I want the position in the
timeline to be the same, so I calculate a new scrollTop for the scrollable
div. Here's a simplified version of what I'm doing:
var self = this;
...
this.zoomIn = function() {
var offset = $("#scrollable").scrollTop();
self.increaseZoomLevel(); // Assume this sets the correct zoom level
var newOffset = offset * self.zoomLevel();
$("#scrollable").scrollTop(newOffset);
};
This works fine. Now I'd like to animate the scrolling. This almost works:
var self = this;
...
this.zoomIn = function() {
var offset = $("#scrollable").scrollTop();
self.increaseZoomLevel(); // Assume this sets the correct zoom level
var newOffset = offset * self.zoomLevel();
$("#scrollable").animate({ scrollTop: newOffset });
};
It works if it's clicked once. However, if a second call to zoomIn happens
while the animation is still running, the newOffset calculation is wrong
because the offset is set to scrollTop() before scrollTop() is correct
since the animation is still manipulating it.
I've tried to use jQuery's queue in various ways to make this calculation
happen first, and that seems to work sometimes:
var self = this;
...
this.zoomIn = function() {
$("#scrollable").queue(function(next) {
var offset = $("#scrollable").scrollTop();
self.increaseZoomLevel(); // Assume this sets the correct zoom level
var newOffset = offset * self.zoomLevel();
next();
}).animate({ scrollTop: newOffset });
};
I think I'm just not understanding queue properly. How do I keep
everything in order even when zoomIn is called repeatedly and rapidly? I
want:
zoomIn x 2 clicks
to give me:
calculate 1 -> animate 1 start -> animate 1 finish -> calculate 2 ->
animate 2 start -> animate 2 finish
and not
calculate 1 -> animate 1 start -> calculate 2 -> animate 1 finish ->
animate 2 start -> animate 2 finish
Because then animate 2 is based on incorrect calculations.
Thanks!
No comments:
Post a Comment