Monday, 18 October 2021

Scroll a web page using Javascript whose scroll triggers at the middle of page

I have encountered some websites which has footer at the bottom and scroll actually happens when I scroll to the area above footer.

To automatically scroll those pages, but the problem with my code currently is it goes at the bottom of the page, where I directly reach footer and hence the scroll trigger which is present just above the footer does not gets triggered.

Is there any way to achieve the same?

This is what I have tried currently which I am executing from the console:

(function() {
    var intervalObj = null;
    var retry = 0;
    var clickHandler = function() { 
        console.log("Clicked; stopping autoscroll");
        clearInterval(intervalObj);
        document.body.removeEventListener("click", clickHandler);
    }
    function scrollDown() { 
        var scrollHeight = document.body.scrollHeight,
            scrollTop = document.body.scrollTop,
            innerHeight = window.innerHeight,
            difference = (scrollHeight - scrollTop) - innerHeight

        if (difference > 0) { 
            window.scrollBy(0, difference);
            if (retry > 0) { 
                retry = 0;
            }
            console.log("scrolling down more");
        } else {
            if (retry >= 3) {
                console.log("reached bottom of page; stopping");
                clearInterval(intervalObj);
                document.body.removeEventListener("click", clickHandler);
            } else {
                console.log("[apparenty] hit bottom of page; retrying: " + (retry + 1));
                retry++;
            }
        }
    }

    document.body.addEventListener("click", clickHandler);

    intervalObj = setInterval(scrollDown, 1000);

})()

There are many websites that has this feature, to test the same one of the website which you can try is

https://www.zomato.com/bangalore/indiranagar-restaurants

Note : The question similar to this does not answer how to scroll at some mid point of page instead it takes me directly to the footer, so this is not a duplicate



from Scroll a web page using Javascript whose scroll triggers at the middle of page

No comments:

Post a Comment