3

I'm trying to add full-page scrolling to the website I'm working on (using React and sadly can't get fullpage.js nor react-fullpage nor any other libs to work with my project).

Basically what I'm trying to do is disabling "normal" scrolling (I use preventDefault() on all scroll keys) and handling scrolling on my own.

Here's an example code:

window.addEventListener("wheel", e => {
        const delta=e.detail? e.detail*(-120) : e.wheelDelta;
        // console.log(delta);

        let direction;
        if ( delta !== null ) {
            direction = delta > 0 ? 'up' : 'down';
        }
        //console.log(direction);

        if(direction === "down"){
            document.querySelector('.who').scrollIntoView({ alignToTop: true, behavior: 'smooth'});
        }
        else if (direction === "up"){
            document.querySelector('.why').scrollIntoView({ alignToTop: true, behavior: 'smooth'});
        }
    });

This code works, however scrollIntoView (it's new functionality and requires polyfill, ik) method is fired only after user has stopped scrolling.

I've recorded my screen to better explain the issue: https://gifyu.com/image/x6Yx (be patient please, stuff starts happening after 2-3s)

As u can see here console starts logging delta and direction immediately after I scroll down, however .scrollIntoView is fired only after mouse scroll wheel stops moving - that's when the site starts scrolling.

Which means that If I just kept moving the mouse wheel down forever scrollIntoView() would never run.

I want scrolling to happen instantly after the user moves scroll wheel up or down. Does anyone has any idea on how to make that happen?

halfer
  • 19,824
  • 17
  • 99
  • 186
devBem
  • 820
  • 4
  • 11
  • 17

1 Answers1

2

It seems that continuously firing .scrollIntoView() and setting the behaviour: 'smooth' parameter is cancelling out the animation as this function is only ment to be called once.

In your code you are trying to smoothly scroll to the direction but by continuously firing the wheel event and therefore continuously calling the .scrollIntoView() function the animation is cancelled out until the animation can play without being interrupted.

That is also the reason why the animation takes place after you stop scrolling.

The way to solve this would be to block any other calls to .scrollIntoView() as long as the scrolling animation is going on. I found this question on how to know when the scrolling is done.

Why did your attempts of adding a fullpage-scrolling react library fail?

zaunermax
  • 46
  • 1
  • 4
  • 1
    Yep, that was precisely the reason. Thank you for spotting that, now everything works as intended. I can't use other libraries because of very specific top navigation behaviour that I need to have. Thanks for your time mate :) – devBem May 22 '18 at 10:09