Blog
Lock and Unlock Page Scroll with jQuery
To lock and unlock page scroll with jQuery, save the current scroll position and the styles you will change, apply a scroll-lock style while the overlay is open, then restore both when it closes. jQuery can handle the buttons and modal events; CSS determines which container can scroll.
This tutorial replaces the older scroll-lock plugin example with a native dialog and a small jQuery controller. The demo locks the background page, keeps long modal content scrollable, supports Escape and a visible close button, and returns you to the previous page position.
Page scroll lock: quick reference
| Requirement | Approach in this example |
|---|---|
| Lock the background | Save offsets, fix the body at those offsets, and hide root/body overflow. |
| Keep modal content reachable | Use a bounded inner region with overflow: auto. |
| Prevent scroll chaining | Apply overscroll-behavior: contain to the modal scroller. |
| Unlock cleanly | Restore the changed inline properties and saved page position. |
| Provide an exit | Keep Close and unlock visible; support native Escape dismissal. |
Live demo: lock and unlock the background page
Open the modal and try scrolling its inner panel. The page behind it should stay in place. Close the modal to restore background scrolling and the previous position.
Try page scroll locking
Open the modal, scroll its content, then close it. The background page is locked while the modal is open and restored afterward.
Use Close and unlock inside the modal or press Escape to return to the article.
Loading. JavaScript, jQuery, and native dialog support are required.
Background scroll is locked
Try scrolling this panel while the background stays still. Close the dialog to restore page scrolling.
Try the inner scrollbar
Scroll this modal panel. The page underneath should remain in place while the dialog is open.
Background position
The demo remembers the page offset before applying the lock. It restores that position when you close the dialog.
Always provide an exit
The Close and unlock button stays above the scrollable content. Escape also closes this native modal dialog.
Keep content reachable
Long modal content belongs in a bounded scrolling region. It should remain reachable with a mouse, keyboard, or touch input.
Restore the original styles
Unlocking restores the inline properties changed by the demo rather than assigning a new overflow value to every page.
Coordinate multiple overlays
A production site with several modals should use one shared scroll-lock manager. This tutorial demonstrates one lock owner.
Test on your target devices
Check mobile Safari and Chrome, virtual keyboards, zoom, sticky headers, and other theme components in your final integration.
End of modal content
You reached the bottom. Scroll upward again or use Close and unlock to return to the article.
Enable JavaScript to try the modal. The download includes the complete source.
1. Understand which element owns the scrollbar
For a small desktop-only experiment, setting the document’s overflow to hidden can suppress its normal scrolling interface:
// Minimal example only; coordinate this with your page's existing styles.
const previousOverflow = document.documentElement.style.overflow;
jQuery(document.documentElement).css('overflow', 'hidden');
// Unlock by restoring the value that was there before.
document.documentElement.style.overflow = previousOverflow;
Do not assume that assigning overflow: auto is a correct restoration for every page. A site may already use a different value or scroll inside an application container. MDN’s overflow reference explains clipping and scroll-container behavior. Hiding overflow is not a general prohibition on all programmatic scrolling.
2. Save the page position before applying the lock
A fixed-body approach can keep the visible background in place while an overlay is open. Record the offset first, then use its negative value as the body’s top position:
// Concept excerpt: the full ZIP also saves existing styles and priorities.
const savedY = window.scrollY;
document.body.style.position = 'fixed';
document.body.style.top = -savedY + 'px';
document.body.style.width = '100%';
On close, restore the original body styles before calling window.scrollTo() with the saved coordinates. The complete implementation records horizontal and vertical offsets, restores only the inline properties it changed, and temporarily disables smooth scrolling while restoring the position.
Removing a classic scrollbar can change available width. The example measures the gap between the viewport and document width, then compensates the body’s right padding while locked. Test your layout if it uses fixed-width calculations, transformed ancestors, unusual horizontal scrolling, or independently fixed widgets.
3. Use a native modal dialog with a clear close control
<dialog id="example-dialog" aria-labelledby="dialog-title">
<h2 id="dialog-title">Demo modal</h2>
<button type="button" id="close-dialog">Close and unlock</button>
<div class="dialog-content">Scrollable modal content...</div>
</dialog>
Open it with showModal() rather than simply adding an open attribute. MDN’s showModal() documentation describes top-layer presentation and how background content becomes inert. This provides modal interaction behavior; the additional styles in this demo define the background scroll policy.
The close button stays above the inner scroller. Escape uses the native dialog’s cancel and close behavior, and the close event performs the same unlock cleanup as the button.
4. Connect open and close actions with jQuery
Attach the event handlers once. Keep restoration in the dialog’s close handler so button and keyboard dismissal share a cleanup path:
// Structural excerpt: lockPage() and unlockPage() are your lock manager.
const dialog = document.querySelector('#example-dialog');
jQuery('#open-dialog').on('click', function () {
lockPage();
dialog.showModal();
});
jQuery('#close-dialog').on('click', function () {
dialog.close();
});
dialog.addEventListener('close', unlockPage);
These excerpts explain the structure; the source ZIP contains the complete lock, restoration, error handling, and focus logic. The jQuery .on() reference documents event-handler attachment. No separate scroll-lock plugin is required.
5. Allow scrolling inside the modal
.dialog-content {
max-height: 50vh;
overflow: auto;
overscroll-behavior: contain;
}
A maximum height creates room for an inner scrollbar when content is long. MDN’s overscroll-behavior reference describes controlling scroll chaining at a scroll container’s boundary. This property helps keep gestures within the modal scroller; it is separate from locking the document underneath.
Avoid globally cancelling every wheel or touchmove event. That can prevent visitors from reaching long dialog content and interfere with other controls. The sample keeps browser scrolling available inside the dialog.
How to lock a single scrollable element
If your goal is to stop one panel rather than the document, change that panel’s overflow and restore it afterward. Keep the unlock control outside the panel so it remains available:
const panel = document.querySelector('#scroll-panel');
const original = panel.style.overflow;
jQuery(panel).css('overflow', 'hidden');
// Later: restore the panel's previous inline value.
panel.style.overflow = original;
This is a basic element example. Production code should preserve property priority as well if it changes a value declared with !important. The downloadable page-lock controller records both values and priorities for its changed properties.
Download and run the scroll-lock project
Extract the ZIP and open index.html in a current browser. The page includes extra background sections so you can scroll before opening the modal. jQuery and its license are bundled; the standalone project works offline without a build step.
jquery-scroll-lock-demo/
├── index.html
├── style.css
├── script.js
├── README.md
└── vendor/
├── jquery-3.7.1.min.js
└── LICENSE-jquery.txt
The download pins jQuery 3.7.1 to match this site’s loaded WordPress version. On WordPress, enqueue the script with the existing jquery dependency instead of adding another library copy. Keep script optimization settings consistent with that loading order.
Testing and integration checklist
Test from a nonzero page offset. Open the modal, scroll over the background and inside the content, reach both ends of the inner scroller, then close with the button and Escape. Confirm that focus returns to the opener and scrolling works after repeated open/close cycles.
Also test the target mobile browsers, zoom, virtual keyboards, sticky headers, and theme overlays. Desktop results do not establish identical behavior on every iOS or Android configuration. The sample has one lock owner. If several components can open overlays, use a shared manager or reference count so one component does not unlock another component’s active overlay.
Common scroll-lock problems
| Problem | What to check |
|---|---|
| The page jumps to the top | Record the offset before fixing the body and restore it after the original styles. |
| The layout shifts sideways | Check scrollbar-width compensation and existing body padding. |
| Modal content will not scroll | Give the inner container a bounded height and overflow: auto. |
| The page remains locked after closing | Run cleanup from every close path, including Escape. |
| A second modal unlocks the first one | Coordinate lock ownership across components. |
| The demo button is disabled | Check JavaScript, jQuery loading order, and native dialog support. |
Frequently asked questions
Does jQuery have a built-in lockScroll() method?
No. The older example used a plugin-provided method. This tutorial uses jQuery events with explicit CSS and restoration logic.
Is overflow hidden enough on every device?
No single short snippet covers all page architectures and browser behaviors. This example combines a fixed body, saved offsets, native dialog behavior, and an inner scroller; test it in your target environment.
Can the user still scroll the modal?
Yes. Its content region has a limited height and its own scrollbar. The background lock does not disable that inner scrolling.
How does Escape unlock the page?
Escape dismisses the native modal, and its close event restores the changed styles and saved page position.
Should I reset the entire body style attribute?
No. That can remove unrelated inline styling. Save and restore the specific properties your lock manager changes.
Can I use this without jQuery?
Yes. Native event listeners can replace the jQuery button bindings. The scroll-lock and dialog APIs already use standard browser features.
Try the complete lock and unlock flow
Use the live modal to inspect background locking and inner scrolling, then download the project to adapt it to your own page. Keep the close control visible and test every restoration path.