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:
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?
Disabling scroll with only CSS. There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.
When the mobile menu is active (overlay) want to prevent that the body is scroll able, disable scroll for body.
I fixed this by adding position: fixed;
to .no-scroll
which is applied to html
and body
when the figure is diplayed.
Added to JS to disable scrolling on open figure:
$('html, body').toggleClass('no-scroll');
Added to JS to enable scrolling on close figure:
$('html, body').removeClass('no-scroll');
CSS:
.no-scroll {
position: fixed;
}
Hopefully this will help others with similar problem.
You can simply disable document scroll with css:
$('body').addClass('overflow'); // use to disable scroll
//-
$('body').removeClass('overflow'); // use to enable scroll
And css: (or use jQuery .css())
<style>
.overflow {
overflow: hidden;
}
</style>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With