Home > Blockchain >  How to override scroll functions in a window?
How to override scroll functions in a window?

Time:03-01

How do you override scroll functions of a browser in JavaScript?

Functions which I was able to find are scroll, scrollBy and scrollTo (from the window object). But, if I try to override them using the standard procedure, like any other function, for example, by executing the following code window.scroll = function(parameter){} it does not have any effect on the browser. So, if I try to scroll the page after executing the above code (for all 3 methods), the window still scrolls.

Are there any other functions which browser uses to scroll? If so, which function should I override to get a custom scrolling behaviour?

I am using Google Chrome (latest version), of course.

CodePudding user response:

The window.scroll, window.scrollTo and window.scrollBy methods do not refer to the native scrolling functionality. They are used to scroll to specific locations on the webpage. If you want to implement a completly custom scrolling functionality/behaviour you need to listen to the wheel event, prevent the default and define your custom behaviour.

Note: changed scroll to wheel event as comment mentioned error

document.addEventListener("wheel", (event) => {
  event.preventDefault();
  event.stopPropagation();
  // now define custom functionality
}, { passive: false });

Instead of window you can also apply it to any other element on the page that has a scrollbar and therefore being scrollable.
Futhermore the wheel event has values for deltaX and deltaY so you can see how much would have been scrolled since the last scroll and you can use the properties x and y to see how much had been scrolled since the beginning.

CodePudding user response:

With Javascript, I'm not sure how to completely prevent the scroll, but you can scroll to a particular location right after they try to scroll, like this:

document.addEventListener('scroll', function(event)
{
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
    window.scrollTo(0,0);
});
<h1>Try to Scroll</h1>
<ol>
  <li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li>
  <li></li><li></li><li></li><li></li><li></li><li></li>
</ol>

Notice that despite my attempts to be thorough, you can still see a little scrolling happen before window.scrollTo(0,0); undoes it.

CSS

If all you're trying to do is prevent scrolling, you can use overflow: hidden with CSS:

html,body { overflow: hidden; }
<h1>Try to Scroll</h1>
<ol>
    <li></li><li></li><li></li><li></li><li></li><li></li>
    <li></li><li></li><li></li><li></li><li></li><li></li>
    <li></li><li></li><li></li><li></li><li></li><li></li>
    <li></li><li></li><li></li><li></li><li></li><li></li>
    <li></li><li></li><li></li><li></li><li></li><li></li>
</ol>

  • Related