The Observer design pattern is a useful way to keep track of the state of objects in a full OO way. We can actually apply this pattern to jQuery animations to keep track of their current state of animated elements during the animation progress. A simple implementation of this pattern is as follows:
var Observer = new function() {
this.position = 0;
this.setPosition = function(pos) {
this.position = pos;
};
this.getPosition = function() {
return this.position;
};
this.observe = function(element) {
element = element || this;
this.setPosition(element.position().left);
alert(this.getPosition());
};
}();
The observe() method of the Observer object will always return the current left offset of an animated element. We can see it in action here:
$(function() {
$('#run').click(function(e) {
Observer.observe($('#animated'));
$('#animated').animate({
left: 100
}, 'slow', function() {
Observer.observe($(this));
$(this).animate({
left: 0
}, 'slow', function() {
Observer.observe($(this));
});
});
e.preventDefault();
});
});
You can see everything in the demo below.