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?
4 Answers
Answers 1
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.
Answers 2
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> Answers 3
I using sth like that:
$.fn.isolatedScroll = -> @on 'mousewheel DOMMouseScroll', (e) -> delta = e.wheelDelta or e.originalEvent and e.originalEvent.wheelDelta or -e.detail bottomOverflow = @scrollTop + $(@).outerHeight() - (@scrollHeight) >= 0 topOverflow = @scrollTop <= 0 if delta < 0 and bottomOverflow or delta > 0 and topOverflow then e.preventDefault() And I use it ie. $(@).find('ul').isolatedScroll()
Answers 4
Disable scrolling in all mobile devices
Kindly check out the answer just below the accepted answer.
0 comments:
Post a Comment