April 21, 2009

Javascript: scroll / animate a background image

I got the urge to add a little flavor to a repeating background image on one of my personal sites. When you roll over the div with your mouse, the image starts scrolling by incrementing the background-position css. First you need a div with a background-image, a background-position, and an id of "header":

#header {
background-image:url(../images/site-header-single.gif);
background-position:-73px 0;
background-repeat:repeat-x;
width:752px;
height:242px;
}

Then you need to attach the mouse rollover functionality to the header - I did this dynamically with protoculous, as seen below in the final Event.observe method. The rest is simple: start a timer, grab the background position offset from the css, increment, and apply the reassembled css. Easy:

// setTimeout variable for clearing on rollout
var headerTimeout;

function addHeaderBehavior() {
Event.observe( $('header'), 'mouseover', startHeaderAnim, false);
Event.observe( $('header'), 'mouseout', stopHeaderAnim, false);
}

function startHeaderAnim() {
headerTimeout = setTimeout( "incrementHeader()", 50 );
}

function incrementHeader()
{
// get x variable of background-position
var bgOffsets = $('header').getStyle('background-position').split(' ');
var offsetX = bgOffsets[0];
var offsetY = bgOffsets[1];
// strip px and increment
offsetX = offsetX.replace( /px/, '' );
offsetX = parseInt( offsetX ) + 1;
// update style
$('header').setStyle( { backgroundPosition:offsetX + 'px ' + offsetY } );

startHeaderAnim();
}

function stopHeaderAnim(event) {
clearTimeout( headerTimeout );
}


Event.observe(window, 'load', addHeaderBehavior, false);

No comments:

Post a Comment