Reputation: 7207
How can I detect the swipe direction without actually scrolling? Here's what I'm doing:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
window.ontouchmove = preventDefault;
window.addEventListener('touchmove', function(e) {
if (e.deltaY < 0) {
console.log('scrolling up');
document.getElementById('status').innerHTML = 'scrolling up';
}
if (e.deltaY > 0) {
console.log('scrolling down');
document.getElementById('status').innerHTML = 'scrolling down';
}
});
<div style='height: 2000px; border: 5px solid gray; touch-action: none;'>
<p id='status'></p>
</div>
What I observe is that although the screen does not scroll, none of the event listener code executes. This is because there is no 'deltaY' property in the event. I used the equivalent code on desktop with the 'wheel' event to detect the scroll direction without scrolling.
Upvotes: 2
Views: 3038
Reputation: 7207
Here's what I did:
let start = null;
window.addEventListener('touchstart', function(e) {
start = e.changedTouches[0];
});
window.addEventListener('touchend', function(e) {
let end = e.changedTouches[0];
if(end.screenY - start.screenY > 0)
{
console.log('scrolling up');
document.getElementById('status').innerHTML = 'scrolling up';
}
else if(end.screenY - start.screenY < 0)
{
console.log('scrolling down');
document.getElementById('status').innerHTML = 'scrolling down';
}
});
Upvotes: 6