'How to implement auto scroll

How to implement auto scroll to next section of webpage on each scroll event but without excluding scroll bar with vanilla JavaScript.

I try with jQuery animate function, with scroll to function and fullpage.js library but no luck



Solution 1:[1]

You could use the scroll() or scrollIntoView() methods to get what you are looking for. The former scrolls based on a pixel offset from the top of the page, whereas the latter scrolls to a given element.


From the MDN:

The Window.scroll() method scrolls the window to a particular place in the document.

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.


For a smooth scrolling, you can in both approaches use the smooth behavior, like this:

// Smoothly scrolls to 200 pixels from the top
window.scroll({top: 200, behavior: 'smooth'});

and

var el = document.getElementById('fooBar');
// Smoothly scrolls to the top of the element provided
el.scrollIntoView({behavior: 'smooth'});

Of course, if you want to do this based on a mousewheel event, you need to setup a listener for that (probably the wheel or scroll event).

Solution 2:[2]

Okay I have the same issue on my project. And I tried to do it with _.throttle or _.debounce functions and I encounter same functionality that is described. I think that if we figure out how to completely prevent scrolling out of throttle functions it will work. But I don't know how to do it. Here is my version of

code:

let screens = ["#id1", "#id2", "#id3", "#id4", 
    "#id5", "#id6", "#id7"];
    let numberOfScreen = 0;
    let isScrolling = false;
    let lastScrollTop = 0;

    document.body.addEventListener("scroll",  _.throttle(()=>{
        var st = window.pageYOffset || document.body.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
        let i = numberOfScreen;
        if (st > lastScrollTop){
            i++;
            if(i >= screens.length){
                i = screens.length-1;
            }
        } else {
            i--;
            if(i<0){
                i = 0;
            }
        }
        window.location = screens[i];
        setTimeout(()=>{
            numberOfScreen = i;
        },1000)
        lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
    }, 1000, { 'trailing': false}));

`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris
Solution 2 Dimitrije Krstic