I simply need to prevent scrolling on a mobile device using JS and/or JQuery when a certain event occurs. I have a figure, when the user opens the figure the scrolling will be disabled, once it is closed, the scrolling will be enabled again. Target devices are:
- any IPhone from 4s up to the latest one (5 + 6 included)
Here are some of the things that I've tried but didn't work out:
Method1 :
document.addEventListener('touchstart', this.touchstart);
document.addEventListener('touchmove', this.touchmove);
function touchstart(e) {
e.preventDefault()
}
function touchmove(e) {
e.preventDefault()
}
Method 2:
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
Any other suggestions?