How to disable scroll without hiding it?
Freeze scrolling while maintaining scrollbar visibility via CSS. Use overflow-y
to keep the scrollbar and position
to cease scrolling. Compensate layout shifts with equal padding-right
and use top
to preserve the user's scroll position:
Toggle the .no-scroll
class on the <body>
tag when you decide to put scrolling on ice.
When toggling on, remember the scroll position:
When you're done, toggle off and defrost:
Enjoy a seamless user experience with this freezing effect on scrolling, no nasty layout shifts and user's scroll position remembered.
Layout shifts prevention
Ensure that our content remains cool
and doesn't jump or shift upon scrolling off:
Detecting page length: Beware of overflow and apply the treatment accordingly.
User experience enhancement
- Remember the scroll position before freezing and apply it afterwards for user-friendly transitions.
- Indulge in smooth scrolling with
scroll-behavior: smooth;
in your CSS or the JavaScript techniques referenced in SitePoint.
JQuery tips
If jQuery is your weapon of choice, here's how you can tame the scroll:
Handling events and cleanup with jQuery’s .off()
can also prove to be handy.
Was this article helpful?