Prevent BODY from scrolling when a modal is opened
To lock scrolling when a modal window is active, add an overflow: hidden;
style to <body>
. The following code snippet toggles this behavior:
Simply call toggleBodyScroll
with true
or false
to control the body's scrollability.
Dealing with various situations
Manage scrolling position
Imposing position:fixed;
on body.modal-open
might make the page jump to the top. You can counteract this by also setting overflow-x: hidden;
on the body—similar to keeping your place in a really good book. 📖
Addressing scrollbar width
The body's content width may change when switching overflow due to a disappearing scrollbar. A smart workaround is to calculate the scrollbar's width and adjust the body's padding when the modal opens.
Ensuring mobile compliance
Consider touch screen users on mobile devices—use touch-action: none;
to prevent scrolling when the modal is open. Care to test on various devices for a seamless experience.
Expanding your toolbox
Utilizing body class
For more control, add a modal-open
class to the body
when the modal opens using JavaScript. This technique provides a fantastic hook for additional stylings or behaviors related to the modal's visibility:
Leveraging jQuery
With jQuery, you can streamline the toggle using the .css()
method, clarifying code like a speck of moonlight through the fog:
Harnessing plugins
Choose jQuery plugins or other libraries giving you extra features for impeccable handling of the modals and scroll behavior—a robust solution tailor-made for different cases.
Caring for legacy browsers
While modern browsers support these solutions, older versions (like IE7+) might need specific workarounds or polyfills. Don't forget about our old friends!
Focusing on accessibility
Handling keyboard navigation
For those navigating with keyboards, ensure their experience isn't spoilt when the modal opens. Make sure modal closures are possible using the Escape key without any scrolling.
Supporting assistive technologies
Make your modals compatible with screen readers and other assistive tools by using correct ARIA roles and attributes. Plugins like a11y-dialog can aid in crafting such accessible modal systems.
Taking care of document flow
When applying your styles, keep the document reflow and repaint cost in mind. Expensive CSS properties can decrease performance, so aim towards properties with a lean effect on flow.
Was this article helpful?