This week I had the opportunity to write a method that wraps the native JavaScript window.scroll
method with one that animates the scroll. The native window.scroll
method is well supported by all Tier-A browsers and is a great way to ensure that dynamic content is visible on the screen. However, it is often jarring to the user when the page jumps to the desired position, so instead we will animate the scrolling.
Example 1: ScrollTo Method
document.scrollTo = function(x, y, n, ms, ease) { var offset = Core.Client.getScrollOffset(), steps = n || 5, i = steps, time = ms || 250, xdiff = x - offset.x, ydiff = y - offset.y, fx = ease ? ease : function(i, steps) { return Math.pow(2, i); }; clearInterval(scrollInterval); scrollInterval = setInterval(function() { i -= 1; var divisor = fx(i, steps); window.scroll(xdiff / divisor + offset.x, ydiff / divisor + offset.y); // last step if (0 === i) { clearInterval(scrollInterval); window.scroll(x, y); } }, time / steps); };
I have attached the scrollTo
method to document, but you can attach it to any object or variable. The getScrollOffset
method is from Core.js and is used to determine how much the user has scrolled the window. The x
and y
parameters are the position that you want to scroll the page too, and is required. The remaining parameters: n
is the number of steps to make for animation (default is 5), ms
is the animation time in milliseconds (default is 250ms), and ease
is the function used to determine each step length. The default easing method is a fractal algorithm where each step length is half the prevent step.
Here are two additional easing functions; the first method is the exact opposite of the default easing method and the second eases with event steps.
Example 2: Easing In
var easeIn = function(i, steps) { return Math.pow(2, steps - i); };
Example 3: Easing None
var easeNone = function(i, steps) { return i; };So, if you wanted to scroll the y-axis to 750 using the
easingInmethod in 10 steps over 500ms, you would callscrollTo
with the following signature:Example 4: ScrollTo Signature
document.scrollTo(0, 750, 10, 500, easeIn);Lastly, the
scrollTo
method properly handles sign, so if you are farther down the page, it will scroll up and if you are farther up the page, it will scroll down.