Skip to content

Instantly share code, notes, and snippets.

@johnwards
Created October 10, 2011 19:41
Show Gist options
  • Save johnwards/1276319 to your computer and use it in GitHub Desktop.
Save johnwards/1276319 to your computer and use it in GitHub Desktop.
Animate a bike or something
function backgroundPosition(obj){
bgPos = obj.css('background-position');
if(typeof(bgPos) === 'undefined') { bgPos = obj.css('background-position-x') + ' ' + obj.css('background-position-y') };
return bgPos;
}
var bike = $("#bike");
var currentPos = parseInt(backgroundPosition(bike).split(" ")[0]);
var frameWidth = parseInt(bike.outerWidth());
var frames = currentPos/frameWidth;
function animate(obj, frames, frameWidth) {
var currentPos = parseInt(backgroundPosition(obj).split(" ")[0]);
if (currentPos == 0) {
obj.css('background-position', ("-"+frameWidth + 'px 0px'));
} else if(currentPos == frames*frameWidth) {
obj.css('background-position', ('0px 0px'));
} else {
var offset = currentPos-frameWidth;
obj.css('background-position', (offset + 'px 0px'));
}
var t = setTimeout(function(){animate(bike, frames, frameWidth)}, 100);
}
animate(bike, frames, frameWidth);
#bike {
width: 530px;
height: 294px;
background: url("../img/bike.png") no-repeat scroll -1060px 0px transparent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment