David Walsh Blog

Background Animations Using MooTools

Updated 4/25/2011: The background animation has been updated to work well with Internet Explorer 7 and 8, and more efficiently with every other browser. This was accomplished by adding the wait property to the animation, and using an initial setStyle assignment to work around an IE8 background-position bug.

One of the sweet effects made easy by JavaScript frameworks like MooTools and jQuery is animation. I ran across this great jQuery tutorial that walks you through animating a background image of a page. Here’s a quick MooTools code snippet that shows you how you can add this sweet effect to any element on a page.


#animate-area	{ 
	background-image: url(clouds.png);
	background-position: 0px 0px;
	background-repeat: repeat-x;

The first step is assigning the image as a background image for our given container. Be sure to repeat the background horizontally!

The MooTools JavaScript

window.addEvent("domready",function() {
	var duration = 40000;
	var length = 2000;
	var count = 0;
	var tweener;
	// Executes the standard tween on the background position
	var run = function() {
		tweener.tween("background-position", "-" + (++count * length) + "px 0px");
	// Defines the tween
	tweener = $("animate-area").setStyle("background-position", "0px 0px").set("tween", { 
		duration: duration, 
		transition: Fx.Transitions.linear,
		onComplete: run,
		link: "cancel"
	// Starts the initial run of the transition

The first step, as always is getting our settings ready for the show. The next piece is putting the animation function in place. We increment the negative background left position counter calculation to keep the show rolling. Last step is playing the show!

Make sure the animation speed is very slow and subtle — a rapid background speed could make your users pass out. On the other hand, implementing it tastefully will make your website unique.