How to disable scrolling temporarily?
Instantly freeze page scrolling by setting overflow: hidden
on <body>
:
This method blocks and unblocks scrolling but does not affect other forms of navigation like keyboard or anchor jumps.
Directions in depth
Managing touch devices scrolling
To prevent scrolling on touch-screen devices, handle touchmove
events:
Important: Use { passive: false }
to successfully prevent the default touch behavior.
Keeping hold of the scroll position
While toggling scrolling, it might be crucial to save the scroll position. This is how you achieve it:
Creating a scrollbar doppelgänger
Prevent UI shift when the scrollbar vanishes by deploying a fake one:
Beyond the Basics
Fluid overflow control
Have a situation where you need to control overflow dynamically, like after an animation or page transition? Here you go:
Handling fussy browsers
Older browsers like IE6 might require alternative methods or polyfills to manage scrolling. Just in case, here's an IE6-friendly approach:
It's critical to validate your solutions across all browsers and devices to ensure it works as expected.
Extra considerations
Preventing scroll chaining
For nested scrollable components, a sly trick is to use overscroll-behavior
to tackle scroll chaining:
Minding performance
Overriding scrolls can impact the user experience and performance. Use judiciously and, as always, think about accessibility and usability.
Was this article helpful?