Kris Groove Kris Groove - 9 days ago 11
Javascript Question

Smooth scroll anchor links WITHOUT jQuery

Is it possible to use smooth scroll to anchor links but without

jQuery
? I am creating a new site and I don't want to use
jQuery
.

Ian Ian
Answer

Using the function from here: JavaScript animation and modifying it to modify a property (not only a style's property), you can try something like this:

function animate(elem, style, unit, from, to, time, prop) {
    if (!elem) {
        return;
    }
    var start = new Date().getTime(),
        timer = setInterval(function () {
            var step = Math.min(1, (new Date().getTime() - start) / time);
            if (prop) {
                elem[style] = (from + step * (to - from))+unit;
            } else {
                elem.style[style] = (from + step * (to - from))+unit;
            }
            if (step === 1) {
                clearInterval(timer);
            }
        }, 25);
    if (prop) {
          elem[style] = from+unit;
    } else {
          elem.style[style] = from+unit;
    }
}

window.onload = function () {
    var target = document.getElementById("div5");
    animate(document.scrollingElement || document.documentElement, "scrollTop", "", 0, target.offsetTop, 2000, true);
};

DEMO: https://jsfiddle.net/zpu16nen/

Make sure you size the window small enough so there's actually a scrollbar and can scroll to the 5th div.

And no, it didn't require the recreation of 25% of jQuery.

This would obviously needly highly modified depending on what your question actually means (like when the window hash changes, or something like that).

Note that with jQuery, it's as easy as:

$(document).ready(function () {
    $("html, body").animate({
        scrollTop: $("#div5").offset().top
    }, 2000);
});

DEMO: http://jsfiddle.net/7TAa2/1/

Just saying...