jQuery: Observer pattern and animations

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;   


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) {
      left: 100
    }, 'slow', function() {
        left: 0
      }, 'slow', function() {


You can see everything in the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.