Body scroll lock — making it work with everything

Body scroll lock — making it work with everything

Image for post

Have a google of how people lock the body scroll and you?ll come across a few solutions to accomplish this. The basic use case is:

  1. Enable some targetElement to appear above the body with position: absolute.
  2. After it appears, use some solution to disable body scrolling so scrolling within the targetElement doesn?t scroll the body content.

Here are the likely solutions you?ll come across:

1. CSS Overflow

This approach works for desktop browsers, and mobile Android. However, it fails for mobile iOS (phone and tablets). OK, let?s try approach #2.

2. Prevent Default

Great solution ? scrolling is blocked! But it also blocks scrolling inside the targetElement. If content in the targetElement has height exceeding the element?s set height, you will want to have it scroll!!!!!

3. Position Fixed

If you make the body position: fixed, the body will scroll to the top thus losing the body?s original scroll position. Not ideal UX!

Proposed Solution ? body-scroll-lock

Body scroll locking that just works with everything ?

Since all devices except iOS respect the overflow: hidden on the html/bodyelements, we can use this approach for these devices.

For iOS ? we check if targetElement has been scrolled to the bottom or top. If it has, then apply the e.preventDefault() solution. Some Javascript is needed to determine this.

The logic to achieve the proposed solution can be found here.

For convenience, the solution can be downloaded as an NPM package body-scroll-lock and used in projects using vanilla JS or frameworks such as React.

(btw, if you found the body-scroll-lock package useful, please star the GitHub repo to help others solve their body scroll locking issues more easily!).


No Responses

Write a response