jQuery animate() and its completion callback

Using jQuery to animate HTML objects is fun. These animations are easy to create and there are many good documents with explanations and examples.

Unfortunately I haven't noticed the information in the jQuery API about "this" in its callback function. The animate-Method replaces "this" with the used DOM-element. If you are trying to program object-oriented with JavaScript, you can easily run into problems.

Here is a little snippet from our game "Doggie Dodge" (working title) to illustrate the problem. The wrong code:

Board.prototype.moveCat = function() {
	// ...
	// As soon as the cat moved, all dogs should start moving
	$('#cat').animate({
			'left' : '+= 20px',
			'top' : '+= 20px'
		}, {
			'duration' : 'fast',
			'complete' : function() {
				this.moveDogs();
			}
		});
	// ...
}

To get this code right, you have to replace "this" through a variable:

Board.prototype.moveCat = function() {
	// ...
	// As soon as the cat moved, all dogs should start moving
	var myBoard = this;
	$('#cat').animate({
			'left' : '+= 20px',
			'top' : '+= 20px'
		}, {
			'duration' : 'fast',
			'complete' : function() {
				myBoard.moveDogs();
			}
		});
	// ...
}

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd><h2> <h3> <h4> <h5> <h6>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or class="OPTIONS" [title="the title"].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.