How to disable scrolling temporarily?
The scroll
event cannot be canceled. But you can do it by canceling these interaction events:
Mouse & Touch scroll and Buttons associated with scrolling.
[Working demo]
// left: 37, up: 38, right: 39, down: 40,// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36var keys = {37: 1, 38: 1, 39: 1, 40: 1};function preventDefault(e) { e.preventDefault();}function preventDefaultForScrollKeys(e) { if (keys[e.keyCode]) { preventDefault(e); return false; }}// modern Chrome requires { passive: false } when adding eventvar supportsPassive = false;try { window.addEventListener("test", null, Object.defineProperty({}, 'passive', { get: function () { supportsPassive = true; } }));} catch(e) {}var wheelOpt = supportsPassive ? { passive: false } : false;var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';// call this to Disablefunction disableScroll() { window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile window.addEventListener('keydown', preventDefaultForScrollKeys, false);}// call this to Enablefunction enableScroll() { window.removeEventListener('DOMMouseScroll', preventDefault, false); window.removeEventListener(wheelEvent, preventDefault, wheelOpt); window.removeEventListener('touchmove', preventDefault, wheelOpt); window.removeEventListener('keydown', preventDefaultForScrollKeys, false);}
UPDATE: fixed Chrome desktop and modern mobile browsers with passive listeners
Do it simply by adding a class to the body:
.stop-scrolling { height: 100%; overflow: hidden;}
Add the class then remove when you want to re-enable scrolling, tested in IE, FF, Safari and Chrome.
$('body').addClass('stop-scrolling')
For mobile devices, you'll need to handle the touchmove
event:
$('body').bind('touchmove', function(e){e.preventDefault()})
And unbind to re-enable scrolling. Tested in iOS6 and Android 2.3.3
$('body').unbind('touchmove')
Here's a really basic way to do it:
window.onscroll = function () { window.scrollTo(0, 0); };
It's kind of jumpy in IE6.