D
D
DeniSidorenko2018-01-29 20:21:01
JavaScript
DeniSidorenko, 2018-01-29 20:21:01

Is there a smooth scroll between anchors in pure JS?

I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2018-01-29
@DeniSidorenko

var linkNav = document.querySelectorAll('[href^="#"]'), //выбираем все ссылки к якорю на странице
    V = 1;  // скорость, может иметь дробное значение через точку (чем меньше значение - тем больше скорость)
for (var i = 0; i < linkNav.length; i++) {
    linkNav[i].addEventListener('click', function(e) { //по клику на ссылку
        e.preventDefault(); //отменяем стандартное поведение
        var w = window.pageYOffset,  // производим прокрутка прокрутка
            hash = this.href.replace(/[^#]*(.*)/, '$1');  // к id элемента, к которому нужно перейти
        t = document.querySelector(hash).getBoundingClientRect().top,  // отступ от окна браузера до id
            start = null;
        requestAnimationFrame(step);  // подробнее про функцию анимации [developer.mozilla.org]
        function step(time) {
            if (start === null) start = time;
            var progress = time - start,
                r = (t < 0 ? Math.max(w - progress/V, w + t) : Math.min(w + progress/V, w + t));
            window.scrollTo(0,r);
            if (r != w + t) {
                requestAnimationFrame(step)
            } else {
                location.hash = hash  // URL с хэшем
            }
        }
    }, false);
}

<a id="scroll" href="#one"></a> <!-- ссылка, по клику на которую осуществляется прокрутка к якорю -->
<a id="one" name="one"></a> <!-- якорь, расположенный в произвольном месте страницы -->

If you're talking about it

I
Ivan Bogachev, 2018-01-29
@sfi0zy

For modern browsers, you don’t need to invent anything, everything is already there . For the rest, you can temporarily polyfill .

A
Andrey Tsvetkov, 2018-01-29
@yellow79

Animation of anything in pure JS https://learn.javascript.ru/js-animation

A
Anton, 2018-01-29
@SPAHI4

https://developer.mozilla.org/en/docs/Web/CSS/scro...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question