1// Experimental: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#Browser_compatibility
2document.body.scrollIntoView({behavior: 'smooth', block: 'start'});
3
1function scrollTo(element, to, duration) {
2 if (duration <= 0) return;
3 var difference = to - element.scrollTop;
4 var perTick = difference / duration * 10;
5
6 setTimeout(function() {
7 element.scrollTop = element.scrollTop + perTick;
8 if (element.scrollTop === to) return;
9 scrollTo(element, to, duration - 10);
10 }, 10);
11}
1// With easing equations:
2
3// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
4window.requestAnimFrame = (function(){
5 return window.requestAnimationFrame ||
6 window.webkitRequestAnimationFrame ||
7 window.mozRequestAnimationFrame ||
8 function( callback ){
9 window.setTimeout(callback, 1000 / 60);
10 };
11})();
12
13// main function
14function scrollToY(scrollTargetY, speed, easing) {
15 // scrollTargetY: the target scrollY property of the window
16 // speed: time in pixels per second
17 // easing: easing equation to use
18
19 var scrollY = window.scrollY || document.documentElement.scrollTop,
20 scrollTargetY = scrollTargetY || 0,
21 speed = speed || 2000,
22 easing = easing || 'easeOutSine',
23 currentTime = 0;
24
25 // min time .1, max time .8 seconds
26 var time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8));
27
28 // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
29 var easingEquations = {
30 easeOutSine: function (pos) {
31 return Math.sin(pos * (Math.PI / 2));
32 },
33 easeInOutSine: function (pos) {
34 return (-0.5 * (Math.cos(Math.PI * pos) - 1));
35 },
36 easeInOutQuint: function (pos) {
37 if ((pos /= 0.5) < 1) {
38 return 0.5 * Math.pow(pos, 5);
39 }
40 return 0.5 * (Math.pow((pos - 2), 5) + 2);
41 }
42 };
43
44 // add animation loop
45 function tick() {
46 currentTime += 1 / 60;
47
48 var p = currentTime / time;
49 var t = easingEquations[easing](p);
50
51 if (p < 1) {
52 requestAnimFrame(tick);
53
54 window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
55 } else {
56 console.log('scroll done');
57 window.scrollTo(0, scrollTargetY);
58 }
59 }
60
61 // call it once to get started
62 tick();
63}
64
65// scroll it!
66scrollToY(0, 1500, 'easeInOutQuint');