Skip to content

Instantly share code, notes, and snippets.

@thuijssoon
Last active November 2, 2023 18:55
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save thuijssoon/fd238517b487a45ce78d8f7ddfa7fee9 to your computer and use it in GitHub Desktop.
Save thuijssoon/fd238517b487a45ce78d8f7ddfa7fee9 to your computer and use it in GitHub Desktop.
iOS disable body scroll
/**
* Prevent body scroll and overscroll.
* Tested on mac, iOS chrome / Safari, Android Chrome.
*
* Based on: https://benfrain.com/preventing-body-scroll-for-modals-in-ios/
* https://stackoverflow.com/a/41601290
*
* Use in combination with:
* html, body {overflow: hidden;}
*
* and: -webkit-overflow-scrolling: touch; for the element that should scroll.
*
* disableBodyScroll(true, '.i-can-scroll');
*/
var disableBodyScroll = (function () {
/**
* Private variables
*/
var _selector = false,
_element = false,
_clientY;
/**
* Polyfills for Element.matches and Element.closest
*/
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function (s) {
var ancestor = this;
if (!document.documentElement.contains(el)) return null;
do {
if (ancestor.matches(s)) return ancestor;
ancestor = ancestor.parentElement;
} while (ancestor !== null);
return el;
};
/**
* Prevent default unless within _selector
*
* @param event object event
* @return void
*/
var preventBodyScroll = function (event) {
if (false === _element || !event.target.closest(_selector)) {
event.preventDefault();
}
};
/**
* Cache the clientY co-ordinates for
* comparison
*
* @param event object event
* @return void
*/
var captureClientY = function (event) {
// only respond to a single touch
if (event.targetTouches.length === 1) {
_clientY = event.targetTouches[0].clientY;
}
};
/**
* Detect whether the element is at the top
* or the bottom of their scroll and prevent
* the user from scrolling beyond
*
* @param event object event
* @return void
*/
var preventOverscroll = function (event) {
// only respond to a single touch
if (event.targetTouches.length !== 1) {
return;
}
var clientY = event.targetTouches[0].clientY - _clientY;
// The element at the top of its scroll,
// and the user scrolls down
if (_element.scrollTop === 0 && clientY > 0) {
event.preventDefault();
}
// The element at the bottom of its scroll,
// and the user scrolls up
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
if ((_element.scrollHeight - _element.scrollTop <= _element.clientHeight) && clientY < 0) {
event.preventDefault();
}
};
/**
* Disable body scroll. Scrolling with the selector is
* allowed if a selector is porvided.
*
* @param boolean allow
* @param string selector Selector to element to change scroll permission
* @return void
*/
return function (allow, selector) {
if (typeof selector !== "undefined") {
_selector = selector;
_element = document.querySelector(selector);
}
if (true === allow) {
if (false !== _element) {
_element.addEventListener('touchstart', captureClientY, false);
_element.addEventListener('touchmove', preventOverscroll, false);
}
document.body.addEventListener("touchmove", preventBodyScroll, false);
} else {
if (false !== _element) {
_element.removeEventListener('touchstart', captureClientY, false);
_element.removeEventListener('touchmove', preventOverscroll, false);
}
document.body.removeEventListener("touchmove", preventBodyScroll, false);
}
};
}());
@thuijssoon
Copy link
Author

Have a look at: https://codepen.io/thuijssoon/pen/prwNjO for a demo.

@LiranCohen
Copy link

Have you tested this on Safari for iPad? It doesn't prevent background scroll.

@psntr
Copy link

psntr commented Sep 4, 2017

It's definitely working on Safari for iPad. Tested on simulator and real iPad.

@bakura10
Copy link

Hi :),

This sseems to be working quite well, thanks for the code! However , while this work properly if the modal/drawer has enough content to scroll, if there is nothing to scroll, touching still move the body. Is there a way to solve this issue?

Thanks!

@rvdsarr
Copy link

rvdsarr commented Apr 7, 2018

Hi!,

Your script is working perfectly for me, except that the overscroll to the top is not working anymore. Is there anyway to still enable this, while still preventing the scroll of the body?

Maybe we can get in contact about this :)

Thanks!

@JonL1
Copy link

JonL1 commented Apr 25, 2018

Not working on iOS 11.3 :(

@multimediavt
Copy link

Per @jonlozano,
There is a fix here:
https://stackoverflow.com/questions/49500339/cant-prevent-touchmove-from-scrolling-window-on-ios

The code will need to be updated for this change.

@brndto
Copy link

brndto commented Jul 23, 2018

Make sure you use 100% instead of 100vh on your modal related elements, this was causing one of our menus to inherit strange scrolling behaviour while allowing body scrolls. 1vh != 1% of viewport on Safari!

@jreviews
Copy link

jreviews commented Aug 3, 2018

Thanks for sharing this. There's an error with the Element.prototype.closest polyfill which is missing the actual "el" variable definition and this generates an error in IE. I believe the correct code would look like this:

		if (!Element.prototype.closest)
		    Element.prototype.closest = function(s) {
		        var el = this;
		        if (!document.documentElement.contains(el)) return null;
		        do {
		            if (el.matches(s)) return el;
		            el = el.parentElement || el.parentNode;
		        } while (el !== null && el.nodeType === 1); 
		        return null;
		    };

@r4fx
Copy link

r4fx commented Mar 4, 2019

Thanks for inspiration, this is the simplest and working solution for me!

@a4jp-com
Copy link

a4jp-com commented Jan 11, 2020

Does this work now? I can't get it to work on my iPhone. iOS 13.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment