Skip to content

Instantly share code, notes, and snippets.

@yuchi
Forked from ryanschuhler/animate-scroll.js
Last active December 21, 2015 06:49
Show Gist options
  • Save yuchi/6266790 to your computer and use it in GitHub Desktop.
Save yuchi/6266790 to your computer and use it in GitHub Desktop.
AUI.add(
'animated-scroll',
function(A) {
// Yes, user agent sniffing.
var scrollTarget = /webkit/i.test(navigator.userAgent) || document.compatMode == 'BackCompat' ?
document.body :
document.documentElement;;
var win = A.getWin();
var DURATION = 'duration',
LEFT = 'left',
SCROLL_TOP = 'scrollTop',
SCROLL_LEFT = 'scrollLeft',
TOP = 'top',
TO = 'to',
X = 'x',
Y = 'y';
var __animations = {};
var __lockHandle = null;
// We're working only on the window, so in environments without the cached sandbox this is important.
if (A.Global.scrollTo) {
A.scrollTo = A.Global.scrollTo;
return;
}
A.Global.animatedScrollConfig = {
duration: 0.8,
stopOnInteraction: false
};
function scrollTo(value, direction) {
if (A.Array.test(value)) {
scrollTo(value[0], SCROLL_LEFT);
scrollTo(value[1], SCROLL_TOP);
return;
}
direction || (direction = SCROLL_TOP);
if (direction === Y || direction === TOP) {
direction = SCROLL_TOP;
}
else if (direction === X || direction === LEFT) {
direction = SCROLL_LEFT;
}
stopAnimation(direction);
getAnimation(value, direction).run();
}
function stopAnimation(direction) {
var anim = __animations[direction];
if (anim) {
unlockInteraction();
anim.stop();
}
}
function getAnimation(value, direction) {
var anim = __animations[direction];
var props = {};
props[direction] = Math.round(value);
if (!anim) {
anim = __animations[direction] = new A.Anim({
node: scrollTarget,
duration: A.Global.animatedScrollConfig.duration,
easing: A.Easing.easeOut,
to: props
});
anim.on({
start: lockInteraction,
end: unlockInteraction
})
}
else {
anim.set(TO, props);
anim.set(DURATION, A.Global.animatedScrollConfig.duration);
}
return anim;
}
function preventDefault(event) {
if (A.Global.animatedScrollConfig.stopOnInteraction) {
stopAnimation();
}
else {
event.preventDefault();
}
}
function lockInteraction() {
if (!__lockHandle) {
__lockHandle = win.on({
keydown: preventDefault,
keypress: preventDefault,
keyup: preventDefault,
mousewheel: preventDefault
});
}
}
function unlockInteraction() {
if (__lockHandle) {
__lockHandle.detach();
__lockHandle = null;
}
}
A.Global.scrollTo = A.scrollTo = scrollTo;
},
'',
{
requires: ['aui-base', 'anim']
}
);
// Automatic animated scroll
AUI().use(
'animated-scroll',
function(A) {
A.getBody().delegate(
'click',
function(event) {
var highlighted = A.one(event.currentTarget.get('hash'));
if (!highlighted) {
return;
}
event.preventDefault();
A.scrollTo(highlighted.getXY())
},
'[href^="#"]'
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment