Skip to content

Instantly share code, notes, and snippets.

@anandthakker
Last active July 3, 2019 09:33
Show Gist options
  • Save anandthakker/2d0e71924285a845f0c4e6c5fd966234 to your computer and use it in GitHub Desktop.
Save anandthakker/2d0e71924285a845f0c4e6c5fd966234 to your computer and use it in GitHub Desktop.
<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