I'm creating a PWA, ASP server side and JS client side. Users interact nicely with it using buttons. The boss ask me if we can implement something like "scroll between app screen" or "perform some operation (edit, delete..) on elements" using the swipe gesture, as many native apps do. Is there an easy way? or any way anyhow? Thanks!
Made an example that logs out the direction of a swipe here: https://jsfiddle.net/jamiesmith/e9gndqpc/3/
Below is the code pulled from the linked example that console logs out the direction of a swipe (up, down, left or right). You can search it for left swipe
or up swipe
etc to find where you would call some function / do something per direction.
It also checks a function called ignoreSwipe
so we can add a class named noswipe
to elements we specifically want to ignore gestures from. It's included because I found, especially with a PWA, you might listen for swipes on a drawer component to close it but may want to ignore swipes from a child element, like a menu item, etc.
let _xDown, _yDown;
document.querySelector('div.app')
.addEventListener(
'touchstart',
handleTouchStart,
false
);
document.querySelector('div.app')
.addEventListener(
'touchmove',
handleTouchMove,
false
);
function ignoreSwipe(event) {
// if some touches come from elements with ignoreswipe class > ignore
return Array.from(event.touches).some((t) =>
t.target.classList.contains('noswipe')
);
}
function handleTouchStart(event) {
if (ignoreSwipe(event)) {
_xDown = undefined;
_yDown = undefined;
return;
}
const firstTouch = event.touches[0];
_xDown = firstTouch.clientX;
_yDown = firstTouch.clientY;
}
function handleTouchMove(event) {
if (!_xDown || !_yDown) {
return;
}
const xUp = event.touches[0].clientX;
const yUp = event.touches[0].clientY;
const xDiff = _xDown - xUp;
const yDiff = _yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
/*most significant*/
if (xDiff > 0) {
/* left swipe */
console.log('app: left swipe ', true);
} else {
/* right swipe */
console.log('app: right swipe ', true);
}
} else {
if (yDiff > 0) {
/* up swipe */
console.log('app: up swipe ', true);
} else {
/* down swipe */
console.log('app: down swipe ', true);
}
}
/* reset values */
_xDown = null;
_yDown = null;
}
Some docs the example makes use of:
TouchEvent.touches - https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches
TouchEvent.touchstart & touchmove - https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
left swipe
or up swipe
etc to find where you would call some function / do something per direction. In the example it console logs the direction. –
Headwater There are a couple of libraries that can help implement touch gestures for PWAs - have a look at Hammerjs:
Your question is fairly generic though, there might be better solutions but that's just one off the top of my head
© 2022 - 2024 — McMap. All rights reserved.