Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ScrollEngine - Small, simple and efficient library for smooth scrolling
// ScrollEngine is a very small, simple, and efficient library for (smooth) scrolling on a web page.
// (C) index.hm 2015, released under the MIT licence - http://opensource.org/licenses/MIT
var EXPORTS = {};
ScrollEngine = new function(){
var _global_id;
// Usage: ScrollEngine._scroll(x:number, y:number)
// ScrollEngine._scroll(element:DOMElement, top:number, left:number)
this._scroll = function(x, y){
var _d = document, _dE = _d.documentElement, _b = _d.body;
var _cx = _dE.scrollLeft || _b.scrollLeft, _cy = _dE.scrollTop || _b.scrollTop;
var _ty = y, _tx = x;
var _id = _global_id = new Date().getTime();
// Do we have a DOM element? If so, work out where to scroll to (plus any specified offset)
if(typeof x == "object"){
y = x.getBoundingClientRect().top - _b.getBoundingClientRect().top + (arguments[2] || 0);
x = x.getBoundingClientRect().left - _b.getBoundingClientRect().left + (arguments[1] || 0);
}
// next defines the "easing" function used for scrolling.
// For smooth scrolling, you'll probably want the default/ease-out.
var next = function(current, target){
var change = (target - current) / 7;
var next = current + change;
// It seems smoother if the cutoff is ~0.1
return (Math.round(next) == Math.round(target) || Math.abs(change) < 0.1) ? true : next;
}
var _keyframe = function(){
// Having a "global" ID invalidates/overrides a previous scroll when a new one is requested
if(_global_id != _id)
return;
var nX = next(_cx, _tx);
var nY = next(_cy, _ty);
// Jump to the next set of co-ordinates
window.scrollTo(Math.round(_cx = (nX === true ? x : nX)), Math.round(_cy = (nY === true ? y : nY)));
if(nX !== true || nY !== true)
window.requestAnimationFrame(_keyframe);
}
window.requestAnimationFrame(_keyframe);
}
EXPORTS._scroll = this._scroll;
}
Owner

Jamie0 commented Sep 3, 2015

A live demo is available on http://index.hm/ :-)

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