Created
September 8, 2017 12:48
-
-
Save Vesely/c302c50d6d02a9a9af9e5d45e60426f9 to your computer and use it in GitHub Desktop.
Stroll To Y (vanilla js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Scroll To | |
*/ | |
// first add raf shim | |
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ | |
window.requestAnimFrame = (function(){ | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
function( callback ){ | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
// main function | |
window.scrollToY = function(scrollTargetY, speed, easing, callback) { | |
// scrollTargetY: the target scrollY property of the window | |
// speed: time in pixels per second | |
// easing: easing equation to use | |
var scrollY = window.scrollY || document.documentElement.scrollTop, | |
currentTime = 0; | |
scrollTargetY = scrollTargetY || 0, | |
speed = speed || 2000, | |
easing = easing || 'easeOutSine'; | |
// min time .1, max time .8 seconds | |
var time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8)); | |
if(!callback) { | |
callback = function() {}; | |
} | |
// easing equations from https://github.com/danro/easing-js/blob/master/easing.js | |
var easingEquations = { | |
easeOutSine: function (pos) { | |
return Math.sin(pos * (Math.PI / 2)); | |
}, | |
easeInOutSine: function (pos) { | |
return (-0.5 * (Math.cos(Math.PI * pos) - 1)); | |
}, | |
easeInOutQuint: function (pos) { | |
if ((pos /= 0.5) < 1) { | |
return 0.5 * Math.pow(pos, 5); | |
} | |
return 0.5 * (Math.pow((pos - 2), 5) + 2); | |
} | |
}; | |
// add animation loop | |
function tick() { | |
currentTime += 1 / 60; | |
var p = currentTime / time; | |
var t = easingEquations[easing](p); | |
if (p < 1) { | |
window.requestAnimFrame(tick); | |
window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t)); | |
} else { | |
// console.log('scroll done'); | |
callback(); | |
window.scrollTo(0, scrollTargetY); | |
} | |
} | |
// call it once to get started | |
tick(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment