Prevent Scrolling Behind a Fixed Overlay and Maintain Scroll Position on Mobile Devices

Published April 4, 2017 | Categories: Web Development
This is a great piece of code if you need to have an overlay on a mobile device and do not want the background to scroll when you have to interact with the overlay.
The below is an example of the javascript. You can change the ‘getElementById’ name to fit with your overlay ID name in the code below, add -webkit-overflow-scrolling: touch; to the #overlay or ID element of your code, and that’s all there is to it.
Example:
(function () {
var _overlay = document.getElementById('overlay');
var _clientY = null; // remember Y position on touch start
_overlay.addEventListener('touchstart', function (event) {
if (event.targetTouches.length === 1) {
// detect single touch
_clientY = event.targetTouches[0].clientY;
}
}, false);
_overlay.addEventListener('touchmove', function (event) {
if (event.targetTouches.length === 1) {
// detect single touch
disableRubberBand(event);
}
}, false);
function disableRubberBand(event) {
var clientY = event.targetTouches[0].clientY - _clientY;
if (_overlay.scrollTop === 0 && clientY > 0) {
// element is at the top of its scroll
event.preventDefault();
}
if (isOverlayTotallyScrolled() && clientY < 0) {
//element is at the top of its scroll
event.preventDefault();
}
}
function isOverlayTotallyScrolled() {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
return _overlay.scrollHeight - _overlay.scrollTop <= _overlay.clientHeight;
}
}())
Source: Stackoverflow
Recent Posts

Hello from Beaconville: High Ed Conference Wrap-Up
View this Story

Cue the Confetti: Celebrating 2022's Higher Ed Wins So Far
View this Story

Beacon Technologies Opens Second Location in Carolina Beach, NC
View this Story

Why You Need Audience Personas For Your Website Content
View this Story