Last active
May 9, 2017 03:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "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