Created
February 23, 2012 22:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated after finding flaw in "right" logic. Incremented and Decremented scrollLeft and value values so totalDistance is consistent throughout the animation.