Skip to content

Instantly share code, notes, and snippets.

@tonytangau
Last active May 9, 2017 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonytangau/04cca5e1a51d1dc0b49513fcd646b394 to your computer and use it in GitHub Desktop.
Save tonytangau/04cca5e1a51d1dc0b49513fcd646b394 to your computer and use it in GitHub Desktop.
Fixed elements (eg. navigation menu, modal dialog) in ios that prevents background scrolling.
// "fixed-element" is the class of the overlay (fixed element) what has "position: fixed"
// Call disableScroll() and enableScroll() to toggle
var freeze = function(e) {
if (!document.getElementsByClassName("fixed-element")[0].contains(e.target)) {
e.preventDefault();
}
}
var disableScroll = function() {
document.body.style.overflow = "hidden"; // Or toggle using class: document.body.className += "overflow-hidden-class";
// Only accept touchmove from fixed-element
document.addEventListener('touchmove', freeze, false);
// Prevent background scrolling
document.getElementsByClassName("fixed-element")[0].addEventListener("touchmove", function(e) {
var top = this.scrollTop,
totalScroll = this.scrollHeight,
currentScroll = top + this.offsetHeight;
if (top === 0 && currentScroll === totalScroll) {
e.preventDefault();
} else if (top === 0) {
this.scrollTop = 1;
} else if (currentScroll === totalScroll) {
this.scrollTop = top - 1;
}
});
}
var enableScroll = function() {
document.removeEventListener("touchmove", freeze);
document.body.style.overflow = "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment