Skip to content

Instantly share code, notes, and snippets.

@wasnertobias
Forked from gblazex/SmoothScroll.js
Last active February 17, 2017 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wasnertobias/50239f1cfddfe33fb0ab to your computer and use it in GitHub Desktop.
Save wasnertobias/50239f1cfddfe33fb0ab to your computer and use it in GitHub Desktop.
// SmoothScroll for websites v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Michael Herf (Pulse Algorithm)
// - Tobias Wasner (optimized & minimized)
(function(){function c(){if(s)return;s=true;if(!document.body)return;var e=document.body;var r=document.documentElement;var a=window.innerHeight;var f=e.scrollHeight;o=document.compatMode.indexOf("CSS")>=0?r:e;u=e;var c=false;if(c){T("keydown",g)}if(l.keyboardSupport&&!c){x("keydown",g)}i=true;if(top!=self){n=true}else if(f>a&&(e.offsetHeight<=a||r.offsetHeight<=a)){var h=false;var p=function(){if(!h&&r.scrollHeight!=document.height){h=true;setTimeout(function(){r.style.height=document.height+"px";h=false},500)}};r.style.height="auto";setTimeout(p,10);if(o.offsetHeight<=a){var d=document.createElement("div");d.style.clear="both";e.appendChild(d)}}if(!l.fixedBackground&&!t){e.style.backgroundAttachment="scroll";r.style.backgroundAttachment="scroll"}}function v(e,t,n,r){r||(r=1e3);C(t,n);if(l.accelerationMax!=1){var i=new Date-d;if(i<l.accelerationDelta){var s=(1+30/i)/2;if(s>1){s=Math.min(s,l.accelerationMax);t*=s;n*=s}}d=new Date}h.push({x:t,y:n,lastX:t<0?.99:-.99,lastY:n<0?.99:-.99,start:+(new Date)});if(p){return}var o=e===document.body;var u=function(){var i=new Date;var s=0;var a=0;for(var f=0;f<h.length;f++){var c=h[f];var d=i-c.start;var v=d>=l.animationTime;var m=v?1:d/l.animationTime;if(l.pulseAlgorithm){m=_(m)}var g=c.x*m-c.lastX>>0;var y=c.y*m-c.lastY>>0;s+=g;a+=y;c.lastX+=g;c.lastY+=y;if(v){h.splice(f,1);f--}}if(o){window.scrollBy(s,a)}else{if(s)e.scrollLeft+=s;if(a)e.scrollTop+=a}if(!t&&!n){h=[]}if(h.length){O(u,e,r/l.frameRate+1)}else{p=false}};O(u,e,0);p=true}function m(e){if(!i&&s)return true;if(!i){c()}var t=e.target;var n=S(t);if(!n||e.defaultPrevented||N(u,"embed")||N(t,"embed")&&/\.pdf/i.test(t.src))return true;var r=e.wheelDeltaX||0;var o=e.wheelDeltaY||0;if(!r&&!o){o=e.wheelDelta||0}if(!l.touchpadSupport&&L(o)){return}if(Math.abs(r)>1.2){r*=l.stepSize/120}if(Math.abs(o)>1.2){o*=l.stepSize/120}v(n,-r,-o);e.preventDefault()}function g(e){var t=e.target;if(/input|textarea|select|embed/i.test(t.nodeName)||t.isContentEditable||e.defaultPrevented||e.ctrlKey||e.altKey||e.metaKey||e.shiftKey&&e.keyCode!=f.spaceBar)return true;if(N(t,"button")&&e.keyCode===f.spaceBar){return true}var n,r=0,i=0;var s=S(u);var o=s.clientHeight;if(s==document.body){o=window.innerHeight}switch(e.keyCode){case f.up:i=-l.arrowScroll;break;case f.down:i=l.arrowScroll;break;case f.spaceBar:n=e.shiftKey?1:-1;i=-n*o*.9;break;case f.pageUp:i=-o*.9;break;case f.pageDown:i=o*.9;break;case f.home:i=-s.scrollTop;break;case f.end:var a=s.scrollHeight-s.scrollTop-o;i=a>0?a+10:0;break;case f.left:r=-l.arrowScroll;break;case f.right:r=l.arrowScroll;break;default:return true}v(s,r,i);e.preventDefault()}function y(e){u=e.target}function E(e,t){for(var n=e.length;n--;)b[w(e[n])]=t;return t}function S(e){var t=[];var r=o.scrollHeight;do{var i=b[w(e)];if(i){return E(t,i)}t.push(e);if(r===e.scrollHeight){if(!n||o.clientHeight+10<r){return E(t,document.body)}}else if(e.clientHeight+10<e.scrollHeight){var s=getComputedStyle(e,"").getPropertyValue("overflow-y");if(s==="scroll"||s==="auto"){return E(t,e)}}}while(e=e.parentNode)}function x(e,t,n){window.addEventListener(e,t,n||false)}function T(e,t,n){window.removeEventListener(e,t,n||false)}function N(e,t){return(e.nodeName||"").toLowerCase()===t.toLowerCase()}function C(e,t){e=e>0?1:-1;t=t>0?1:-1;if(r.x!==e||r.y!==t){r.x=e;r.y=t;h=[];d=0}}function L(e){if(!e)return;e=Math.abs(e);a.push(e);a.shift();clearTimeout(k);return!(A(a[0],120)&&A(a[1],120)&&A(a[2],120))}function A(e,t){return e%t==0}function M(e){var t,n,r;e=e*l.pulseScale;if(e<1){t=e-(1-Math.exp(-e))}else{n=Math.exp(-1);e-=1;r=1-Math.exp(-e);t=n+r*(1-n)}return t*l.pulseNormalize}function _(e){if(e>=1)return 1;if(e<=0)return 0;if(l.pulseNormalize==1){l.pulseNormalize/=M(1)}return M(e)}var e={frameRate:150,animationTime:400,stepSize:120,pulseAlgorithm:true,pulseScale:8,pulseNormalize:1,accelerationDelta:20,accelerationMax:1,keyboardSupport:true,arrowScroll:50,touchpadSupport:true,fixedBackground:true,excluded:""};var t=false;var n=false;var r={x:0,y:0};var i=false;var s=false;var o=document.documentElement;var u;var a=[120,120,120];var f={left:37,up:38,right:39,down:40,spaceBar:32,pageUp:33,pageDown:34,end:35,home:36};var l=e;var h=[];var p=false;var d=new Date;var b={};setInterval(function(){b={}},10*1e3);var w=function(){var e=0;return function(t){return t.uniqueID||(t.uniqueID=e++)}}();var k;var O=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||function(e,t,n){k=window.setTimeout(e,n||1e3/60)}}();var D=/chrome/i.test(window.navigator.userAgent);var P;if("onwheel"in document.createElement("div"))P="wheel";else if("onmousewheel"in document.createElement("div"))P="mousewheel";if(P&&D){x(P,m);x("mousedown",y);x("load",c)}})()
// SmoothScroll for websites v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Michael Herf (Pulse Algorithm)
// - Tobias Wasner (optimized)
(function(){
// Scroll Variables (tweakable)
var defaultOptions = {
// Scrolling Core
frameRate : 150, // [Hz]
animationTime : 400, // [px]
stepSize : 120, // [px]
// Pulse (less tweakable)
// Ratio of "tail" to "acceleration"
pulseAlgorithm : true,
pulseScale : 8,
pulseNormalize : 1,
// Acceleration
accelerationDelta : 20, // 20
accelerationMax : 1, // 1
// Keyboard Settings
keyboardSupport : true, // option
arrowScroll : 50, // [px]
// Other
touchpadSupport : true,
fixedBackground : true,
excluded : ""
};
// Other Variables
var isExcluded = false;
var isFrame = false;
var direction = {x: 0, y: 0};
var initDone = false;
var initTried = false;
var root = document.documentElement;
var activeElement;
var deltaBuffer = [120, 120, 120];
var key = {left: 37, up: 38, right: 39, down: 40, spaceBar: 32, pageUp: 33, pageDown: 34, end: 35, home: 36};
/***********************************************
* SETTINGS
***********************************************/
var options = defaultOptions;
/***********************************************
* INITIALIZE
***********************************************/
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (initTried) return;
initTried = true;
if (!document.body) return;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// Check compatibility mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
var disableKeyboard = false;
/**
* Tests if smooth scrolling is allowed. Shuts down everything if not.
*/
// Disable keyboard support if anything above requested it
if (disableKeyboard) {
removeEvent("keydown", keyDown);
}
if (options.keyboardSupport && !disableKeyboard) {
addEvent("keydown", keyDown);
}
initDone = true;
// Checks if this script is running in a frame
if (top != self) {
isFrame = true;
} else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) {
/**
* This fixes a bug where the areas left and right to
* the content does not trigger the onMouseWheel event
* on some pages. e.g.: html, body { height: 100% }
*/
// DOMChange (throttle): fix height
var pending = false;
var refresh = function () {
if (!pending && html.scrollHeight != document.height) {
pending = true; // add a new pending action
setTimeout(function () {
html.style.height = document.height + 'px';
pending = false;
}, 500); // Act rarely to stay fast
}
};
html.style.height = 'auto';
setTimeout(refresh, 10);
// Clear fix
if (root.offsetHeight <= windowHeight) {
var underlay = document.createElement("div");
underlay.style.clear = "both";
body.appendChild(underlay);
}
}
// Disable fixed background
if (!options.fixedBackground && !isExcluded) {
body.style.backgroundAttachment = "scroll";
html.style.backgroundAttachment = "scroll";
}
}
/************************************************
* SCROLLING
************************************************/
var queue = [];
var pending = false;
var lastScroll = new Date;
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
directionCheck(left, top);
if (options.accelerationMax != 1) {
var elapsed = new Date - lastScroll;
if (elapsed < options.accelerationDelta) {
var factor = (1 + (30 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, options.accelerationMax);
left *= factor;
top *= factor;
}
}
lastScroll = new Date;
}
// Push a scroll command
queue.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: +new Date
});
// Don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function () {
var now = new Date;
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < queue.length; i++) {
var item = queue[i];
var elapsed = now - item.start;
var finished = (elapsed >= options.animationTime);
// Scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / options.animationTime;
// Easing (optional)
if (options.pulseAlgorithm) {
position = pulse(position);
}
// Only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// Update last values
item.lastX += x;
item.lastY += y;
// Delete and step back if it's over
if (finished) {
queue.splice(i, 1); i--;
}
}
// Scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY);
} else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// Clean up if there's nothing left to do
if (!left && !top) {
queue = [];
}
if (queue.length) {
requestFrame(step, elem, (delay / options.frameRate + 1));
} else {
pending = false;
}
};
// Start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* @param {Object} event
*/
function wheel(event) {
if (!initDone && initTried) return true;
if (!initDone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// Use default if there's no overflowing
// Element or default action is prevented
if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") || (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) return true;
var deltaX = event.wheelDeltaX || 0;
var deltaY = event.wheelDeltaY || 0;
// Use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = event.wheelDelta || 0;
}
// Check if it's a touchpad scroll that should be ignored
if (!options.touchpadSupport && isTouchpad(deltaY)) {
return
}
// Scale by step size
// Delta is 120 most of the time
// Synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= options.stepSize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= options.stepSize / 120;
}
scrollArray(overflowing, -deltaX, -deltaY);
event.preventDefault();
}
/**
* KeyDown event handler.
* @param {Object} event
*/
function keyDown(event) {
var target = event.target;
// Do nothing if user is editing text or using a modifier key (except shift) or in a dropdown
if (/input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || (event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode != key.spaceBar))) return true;
// Space bar should trigger button press
if (isNodeName(target, "button") && event.keyCode === key.spaceBar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -options.arrowScroll;
break;
case key.down:
y = options.arrowScroll;
break;
case key.spaceBar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageUp:
y = -clientHeight * 0.9;
break;
case key.pageDown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -options.arrowScroll;
break;
case key.right:
x = options.arrowScroll;
break;
default:
return true; // A key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
}
/**
* MouseDown event only for updating activeElement
*/
function mouseDown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var cache = {}; // Cleared out every once in while
setInterval(function () { cache = {}; }, 10 * 1000);
var uniqueID = (function () {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
function setCache(elements, overflowing) {
for (var i = elements.length; i--;)
cache[uniqueID(elements[i])] = overflowing;
return overflowing;
}
function overflowingAncestor(value) {
var elements = [];
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(value)];
if (cached) {
return setCache(elements, cached);
}
elements.push(value);
if (rootScrollHeight === value.scrollHeight) {
if (!isFrame || root.clientHeight + 10 < rootScrollHeight) {
return setCache(elements, document.body); // Scrolling root in WebKit
}
} else if (value.clientHeight + 10 < value.scrollHeight) {
var overflow = getComputedStyle(value, "").getPropertyValue("overflow-y");
if (overflow === "scroll" || overflow === "auto") {
return setCache(elements, value);
}
}
} while (value = value.parentNode);
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||"").toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
queue = [];
lastScroll = 0;
}
}
var deltaBufferTimer;
function isTouchpad(deltaY) {
if (!deltaY) return;
deltaY = Math.abs(deltaY);
deltaBuffer.push(deltaY);
deltaBuffer.shift();
clearTimeout(deltaBufferTimer);
return !(isDivisible(deltaBuffer[0], 120) && isDivisible(deltaBuffer[1], 120) && isDivisible(deltaBuffer[2], 120));
}
function isDivisible(n, divisor) {
return (n%divisor == 0);
}
var requestFrame = (function () {
return (window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (callback, element, delay) { deltaBufferTimer = window.setTimeout(callback, delay || (1000/60)); });
})();
/***********************************************
* PULSE
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// Test
x = x * options.pulseScale;
if (x < 1) { // Acceleration
val = x - (1 - Math.exp(-x));
} else { // tail
// The previous animation ended here:
start = Math.exp(-1);
// Simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * options.pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (options.pulseNormalize == 1) {
options.pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
var isChrome = /chrome/i.test(window.navigator.userAgent);
var wheelEvent;
if ("onwheel" in document.createElement("div"))
wheelEvent = "wheel";
else if ("onmousewheel" in document.createElement("div"))
wheelEvent = "mousewheel";
if (wheelEvent && isChrome) {
addEvent(wheelEvent, wheel);
addEvent("mousedown", mouseDown);
addEvent("load", init);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment