'How to override scroll functions in a window?
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.
Solution 1:[1]
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>
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 |
