Skip to content

Instantly share code, notes, and snippets.

@hayes0724
Created August 20, 2021 02:19
Show Gist options
  • Save hayes0724/853ac923d5882ef328495d7bf80aac69 to your computer and use it in GitHub Desktop.
Save hayes0724/853ac923d5882ef328495d7bf80aac69 to your computer and use it in GitHub Desktop.
Class for creating touch and swipe events
export class TouchHandler {
#xDown = null
#yDown = null
/**
* Handles touch events for selected element
* @param {Element|string} element
*/
constructor(element) {
this.element = typeof(element) === 'string' ? document.querySelector(element) : element
this.element.addEventListener('touchstart', (event) => {
this.#xDown = event.touches[0].clientX
this.#yDown = event.touches[0].clientY
})
}
/**
* Callback function for swiping left
* @param {CallableFunction} callback
* @return {TouchHandler}
*/
swipeLeft(callback) {
this.swipeLeft = callback;
return this;
}
/**
* Callback function for swiping left
* @param {CallableFunction} callback
* @return {TouchHandler}
*/
swipeRight(callback) {
this.swipeRight = callback;
return this;
}
/**
* Callback function for swiping up
* @param {CallableFunction} callback
* @return {TouchHandler}
*/
swipeUp(callback) {
this.swipeUp = callback;
return this;
}
/**
* Callback function for swiping down
* @param {CallableFunction} callback
* @return {TouchHandler}
*/
swipeDown(callback) {
this.swipeDown = callback;
return this;
}
/**
* Add the touch events after creating callbacks
*/
run() {
this.element.addEventListener('touchmove', (event) => {
this._handleTouchMove(event)
})
console.log(this)
}
/**
* Determine the direction of touch event
* @param {Event} event
* @private
*/
_handleTouchMove(event) {
if ( ! this.#xDown || ! this.#yDown ) {
return;
}
const xUp = event.touches[0].clientX;
const yUp = event.touches[0].clientY;
this.xDiff = this.#xDown - xUp;
this.yDiff = this.#yDown - yUp;
if ( Math.abs( this.xDiff ) > Math.abs( this.yDiff ) ) {
if ( this.xDiff > 0 ) {
this.swipeLeft();
} else {
this.swipeRight();
}
} else {
if ( this.yDiff > 0 ) {
this.swipeUp();
} else {
this.swipeDown();
}
}
// 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