Last active
July 3, 2019 09:33
-
-
Save anandthakker/2d0e71924285a845f0c4e6c5fd966234 to your computer and use it in GitHub Desktop.
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
<html> | |
<head> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<div id="widget" style="width: 100%; height: 300px; background-color: #aacccc">It should not be possible to initiate a page scroll from within this element</div> | |
<div style="width: 100%; height: 50px; background-color: #ccc"></div> | |
<div style="width: 100%; height: 50px; background-color: #fff"></div> | |
<div style="width: 100%; height: 50px; background-color: #ccc"></div> | |
<div style="width: 100%; height: 50px; background-color: #fff"></div> | |
<div style="width: 100%; height: 50px; background-color: #ccc"></div> | |
<div style="width: 100%; height: 50px; background-color: #fff"></div> | |
<div style="width: 100%; height: 50px; background-color: #ccc"></div> | |
<div style="width: 100%; height: 50px; background-color: #fff"></div> | |
<div style="width: 100%; height: 50px; background-color: #ccc"></div> | |
<script> | |
const div = document.getElementById('widget'); | |
div.addEventListener('touchstart', function () { | |
console.log('div touchstart') | |
bindDocumentHandler(); | |
}, {passive: true}) | |
function onMove(e) { | |
const cancelable = e.cancelable; | |
e.preventDefault(); | |
const defaultPrevented = e.defaultPrevented; | |
console.log(`document ${e.type}`, {cancelable, defaultPrevented}); | |
} | |
function bindDocumentHandler() { | |
console.log('Bind document handlers'); | |
window.document.addEventListener('touchmove', onMove, {passive: false}); | |
window.document.addEventListener('touchend', () => { | |
window.document.removeEventListener('touchmove', onMove, {passive: false}); | |
}); | |
} | |
// The above code should be sufficient to prevent scrolling | |
// initiated from within #widget, but it's not. In order to make it | |
// work, we have to either bind the following non-passive handler: | |
// div.addEventListener('touchmove', function () { | |
// console.log('div touchmove - passive: false') | |
// }, {passive: false}); | |
// or else call `bindDocumentHandlers()` directly (instead of | |
// within the touchstart handler above: | |
// bindDocumentHandler(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment