Time for action – animating the background position

Now for the <script> itself. At the bottom of the HTML file, in the empty function as usual, add the following code:

var bg = $("#background"),
  mg = $("#midground"),
  fg = $("#foreground");

$(document).keydown(function(e) {

  if (e.which === 39) { 
    bg.animate({ "backgroundPosition": "-=1px" }, 0, "linear");
    mg.animate({ "backgroundPosition": "-=10px" }, 0, "linear" );
    fg.animate({ "backgroundPosition": "-=20px" }, 0, "linear" );
  }
});

If we run this page in a browser now, we should find that as we hold down the right arrow key, the different background slices move at progressively slower speeds with the foreground almost rushing past, and the background moving along leisurely.

What just happened?

Get jQuery 1.4 Animation Techniques Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.