3

I'm trying to imitate scrollTop (jQuery) in vanilla JS, so on click it scrolls to an element. This works fine - unless you have already scrolled past the element. So it doesn't scroll the opposite way. Should my formula incorporate window.pageYOffset?

var moves = function(scrollz) {
    var scrollPos = document.getElementById(scrollz).offsetTop - ((document.documentElement.clientHeight - document.getElementById(scrollz).offsetHeight) / 2);

    var timerID = setInterval(function() {
        window.scrollBy(0, speed);
        if (window.pageYOffset >= scrollPos) {
            clearInterval(timerID);
        }
    }, 13);
}
0

1 Answer 1

4

scrollBy will scroll from "actual position" to "number of pixel defined" I think you might take a look at scrollTo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Philippe, i just set a counter starting at window.pageYOffset and incremented it at setintervals till scrollPos[above] was reached

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.