0

I made a code that makes scrolling smoother and with a slow deceleration, but ah a bug, which I am not able to resolve, after scrolling through the mouse wheel, if I instantly click on another height of the scroll bar, it still continues to finish the animation where it left off. I would like help to resolve this.

function initiateScrollSmooth(speed, smooth) {
    const target = document.documentElement || document.body

    var moving = false
    var pos = target.scrollTop
    target.addEventListener('wheel', scrolled, { passive: false })
    function scrolled(e) {
        e.preventDefault(); // disable default scrolling

        var delta = Math.sign(e.deltaY * -1)

        pos += -delta * speed
        pos = Math.max(0, Math.min(pos, target.scrollHeight - target.clientHeight))

        if (!moving) update()
    }
    function update() {
        moving = true

        const delta = (pos - target.scrollTop) / smooth

        target.scrollTop += delta

        if (Math.abs(delta) > 0.5)
            window.requestAnimationFrame(update)
        else
            moving = false
    }
}
initiateScrollSmooth(150, 3)

example: https://streamable.com/9svn3r

reproduces: add this script in your page.

<script src="https://vandsonfalcao.vercel.app/scripts/scroll.js"></script>

credits: Smooth vertical scrolling on mouse wheel in vanilla javascript?

I don't know how to resolve this. thank you for the help.

0 Answers0