Skip to content

Instantly share code, notes, and snippets.

@jsmithdev
Created July 8, 2021 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsmithdev/89b0050f38b15bc782a4f6e8bf54378b to your computer and use it in GitHub Desktop.
Save jsmithdev/89b0050f38b15bc782a4f6e8bf54378b to your computer and use it in GitHub Desktop.
swipe actions in an lwc app
renderedCallback() {
// swipe to close
this.template
.querySelector('div.app')
.addEventListener(
'touchstart',
this.handleTouchStart.bind(this),
false
);
this.template
.querySelector('div.app')
.addEventListener(
'touchmove',
this.handleTouchMove.bind(this),
false
);
}
getTouches(event) {
return event.touches;
}
ignoreSwipe(event) {
// if some touches come from elements with ignoreswipe class > ignore
return Array.from(event.touches).some((t) =>
t.target.classList.contains('noswipe')
);
}
handleTouchStart(event) {
if (this.ignoreSwipe(event)) {
this._xDown = undefined;
this._yDown = undefined;
return;
}
const firstTouch = this.getTouches(event)[0];
this._xDown = firstTouch.clientX;
this._yDown = firstTouch.clientY;
}
handleTouchMove(event) {
if (!this._xDown || !this._yDown) {
return;
}
const xUp = event.touches[0].clientX;
const yUp = event.touches[0].clientY;
const xDiff = this._xDown - xUp;
const yDiff = this._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 */
this._xDown = null;
this._yDown = null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment