diff --git a/README.md b/README.md index 512c497..1e855d5 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ button.addEventListener('click', function () { document.body, // element to scroll with (most of times you want to scroll with whole ) 0, // target scrollY (0 means top of the page) 10000, // duration in ms + true, // horizontal scrolling? function() { // callback function that runs after the animation (optional) console.log('done!') } diff --git a/animatedScrollTo.js b/animatedScrollTo.js index bc7d0cb..cc221ec 100644 --- a/animatedScrollTo.js +++ b/animatedScrollTo.js @@ -8,8 +8,12 @@ return -c/2 * (t*(t-2) - 1) + b; }; - var animatedScrollTo = function (element, to, duration, callback) { - var start = element.scrollTop, + var animatedScrollTo = function (element, to, duration, scrollLeft, callback) { + + var direction = 'scrollTop' + if (scrollLeft) direction = 'scrollLeft' + + var start = element[direction], change = to - start, animationStart = +new Date(); var animating = true; @@ -17,26 +21,26 @@ var animateScroll = function() { if (!animating) { + if (callback) { callback(); } return; } requestAnimFrame(animateScroll); var now = +new Date(); var val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration)); if (lastpos) { - if (lastpos === element.scrollTop) { + if (lastpos === element[direction]) { lastpos = val; - element.scrollTop = val; + element[direction] = val; } else { animating = false; } } else { lastpos = val; - element.scrollTop = val; + element[direction] = val; } if (now > animationStart + duration) { - element.scrollTop = to; + element[direction] = to; animating = false; - if (callback) { callback(); } } }; requestAnimFrame(animateScroll);