Skip to content

Instantly share code, notes, and snippets.

@JamesEggers1
Created February 23, 2012 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesEggers1/1895331 to your computer and use it in GitHub Desktop.
Save JamesEggers1/1895331 to your computer and use it in GitHub Desktop.
A simple, recursive animation algorithm for scrolling an element over a certain duration.
function slide(element, value, duration, total) {
if (!total) { total = 0;}
if (total >= duration) {return;}
var startLocation = element.scrollLeft;
var totalDistance = Math.abs(value - startLocation);
var step = 25;
var direction = (startLocation < value) ? "left" : "right";
var iteration = duration / step;
var iterationDistance = totalDistance / iteration;
if (direction === "left") {
element.scrollLeft += iterationDistance;
value += iterationDistance;
} else {
element.scrollLeft -= iterationDistance;
value -= iterationDistance;
}
setTimeout(function() {slide(element, value, duration, total += step);}, step);
}
/***********************
usage:
***********************/
var viewport= document.getElementById("my-viewport");
slide(viewport, 500, 200);
@JamesEggers1
Copy link
Author

Updated after finding flaw in "right" logic. Incremented and Decremented scrollLeft and value values so totalDistance is consistent throughout the animation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment