Skip to content

Instantly share code, notes, and snippets.

@StrongerMyself
Last active July 5, 2019 06:40
Show Gist options
  • Save StrongerMyself/f0b0d6f13f36a743b0932574aca101bf to your computer and use it in GitHub Desktop.
Save StrongerMyself/f0b0d6f13f36a743b0932574aca101bf to your computer and use it in GitHub Desktop.
detect touch swipe (none, left, right, up, down)
export type SwipeDirect = ('none' | 'left' | 'right' | 'up' | 'down')
export interface ISwipeDetect {
direct: SwipeDirect
offsetDist: number
startX: number
startY: number
distX: number
distY: number
init: () => void
detstroy: () => void
onTouchStart: (e?) => void
onTouchMove: (e?) => void
onTouchEnd: (e?) => void
}
function SwipeDetect(_elem) {
const elem = _elem
this.direct = 'none'
this.offsetDist = 30
this.startX = 0
this.startY = 0
this.distX = 0
this.distY = 0
const onTouchStart = (e) => {
let touchobj = e.changedTouches[0]
this.direct = 'none'
this.startX = this.distX = touchobj.pageX
this.startY = this.distY = touchobj.pageY
this.onTouchStart(e)
}
const onTouchMove = (e) => {
let touchobj = e.changedTouches[0]
this.distX = touchobj.pageX - this.startX
this.distY = touchobj.pageY - this.startY
this.onTouchMove(e)
}
const onTouchEnd = (e) => {
let absDistX = Math.abs(this.distX)
let absDistY = Math.abs(this.distY)
let isHorizon = (absDistX > this.offsetDist)
let isVerical = (absDistY > this.offsetDist)
if (isHorizon) {
this.direct = (this.distX < 0) ? 'left' : 'right'
this.onTouchEnd(e)
} else if (isVerical) {
this.direct = (this.distY < 0) ? 'up' : 'down'
this.onTouchEnd(e)
}
}
this.init = () => {
elem.addEventListener('touchstart', onTouchStart, false)
elem.addEventListener('touchmove', onTouchMove, false)
elem.addEventListener('touchend', onTouchEnd, false)
}
this.detstroy = () => {
elem.removeEventListener('touchstart', onTouchStart, false)
elem.removeEventListener('touchmove', onTouchMove, false)
elem.removeEventListener('touchend', onTouchEnd, false)
}
this.onTouchStart = (e) => { }
this.onTouchMove = (e) => { }
this.onTouchEnd = (e) => { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment