showing results for - "animated scroll to anchor without jquery"
Athénaïs
16 Aug 2016
1function animate(elem, style, unit, from, to, time, prop) {
2    if (!elem) {
3        return;
4    }
5    var start = new Date().getTime(),
6        timer = setInterval(function () {
7            var step = Math.min(1, (new Date().getTime() - start) / time);
8            if (prop) {
9                elem[style] = (from + step * (to - from))+unit;
10            } else {
11                elem.style[style] = (from + step * (to - from))+unit;
12            }
13            if (step === 1) {
14                clearInterval(timer);
15            }
16        }, 25);
17    if (prop) {
18          elem[style] = from+unit;
19    } else {
20          elem.style[style] = from+unit;
21    }
22}
23
24window.onload = function () {
25    var target = document.getElementById("div5");
26    animate(document.scrollingElement || document.documentElement, "scrollTop", "", 0, target.offsetTop, 2000, true);
27};
28
Maximilian
22 Aug 2018
1const requestAnimationFrame = window.requestAnimationFrame ||
2    window.webkitRequestAnimationFrame ||
3    window.mozRequestAnimationFrame ||
4    window.oRequestAnimationFrame ||
5    window.msRequestAnimationFrame;
6
7function scrollTo(to) {
8    const start = window.scrollY || window.pageYOffset
9    const time = Date.now()
10    const duration = Math.abs(start - to) / 3;
11
12    (function step() {
13        var dx = Math.min(1, (Date.now() - time) / duration)
14        var pos = start + (to - start) * easeOutQuart(dx)
15
16        window.scrollTo(0, pos)
17
18        if (dx < 1) {
19            requestAnimationFrame(step)
20        }
21    })()
22}
23