JavaScript Background Scroller

Of the many developer blogs that I read, one of my favorites is that of David Walsh. Recently he posted an update of a small function he’d written to scroll a background image constantly to easily add movement to a page. While his functions are good (with one admitted error, now fixed), many of the comments people left asked about adding parallax.

I quickly saw a solution to this, so I put together a simple method to do parallax background scrolling based off of David’s original code.

bgScroller = new Class({

 Implements: [Events, Options],

 options: {
  duration: 40000

 tweener: null,
 length: 0,
 count: 0,
 verticalPosition: null,

 run: function() {
  this.tweener.tween('background-position', ('-' + (++this.count * this.length) + 'px ' + this.verticalPosition));

 initialize: function(element, options){
  this.tweener = element;
  this.length = this.tweener.getSize().x;
  this.verticalPosition = this.tweener.getStyle("background-position").split(" ")[1];
  this.tweener.setStyle("background-position", ("0px " + this.verticalPosition));
  this.tweener.set('tween', {
   duration: this.options.duration,
   transition: Fx.Transitions.linear,
   link: "cancel"


All I’ve done is taken his code and converted it to a class structure. This allows us to have multiple instances of the function running in parallel. All we need to do is instantiate the class for each layer.

window.addEvent("domready", function() {
 var frontScroller = new bgScroller($("front"), { duration: 9000 });
 var middleScroller = new bgScroller($("middle"), { duration: 85000 });
 var backScroller = new bgScroller($("back"), { duration: 55000 });

You can see a quick demo of this functionality here.

Please note that this class requires MooTools 1.3+. It may work with 1.2, but I haven’t tested it.

So please check out David’s blog. I take no credit for the idea of a background scroller or the code to do it. I’ve only restructured it.

About Dark Prism

I'm a Front-End Web Developer from Lancaster, PA. I like zombies, video games (Minecraft, Left 4 Dead), and StumbleUpon.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>