Skip to content

Instantly share code, notes, and snippets.

@Semdevmaster
Created May 29, 2021 10:39
Show Gist options
  • Select an option

  • Save Semdevmaster/df045f7480712860d54714a4d36e1667 to your computer and use it in GitHub Desktop.

Select an option

Save Semdevmaster/df045f7480712860d54714a4d36e1667 to your computer and use it in GitHub Desktop.
Add swipe functionality to element
class Swipe {
constructor (element) {
this.xDown = null
this.yDown = null
this.element = typeof (element) === 'string' ? document.querySelector(element) : element
this.element.addEventListener('touchstart', (evt) => {
this.xDown = evt.touches[0].clientX
this.yDown = evt.touches[0].clientY
})
}
onLeft (callback) {
this.onLeft = callback
return this
};
onRight (callback) {
this.onRight = callback
return this
};
onUp (callback) {
this.onUp = callback
return this
};
onDown (callback) {
this.onDown = callback
return this
};
handleTouchMove (evt) {
if (!this.xDown || !this.yDown) {
return
}
let xUp = evt.touches[0].clientX
let yUp = evt.touches[0].clientY
this.xDiff = this.xDown - xUp
this.yDiff = this.yDown - yUp
if (Math.abs(this.xDiff) !== 0) {
if (this.xDiff > 2) {
typeof (this.onLeft) === 'function' && this.onLeft()
} else if (this.xDiff < -2) {
typeof (this.onRight) === 'function' && this.onRight()
}
}
if (Math.abs(this.yDiff) !== 0) {
if (this.yDiff > 2) {
typeof (this.onUp) === 'function' && this.onUp()
} else if (this.yDiff < -2) {
typeof (this.onDown) === 'function' && this.onDown()
}
}
this.xDown = null
this.yDown = null
};
run () {
this.element.addEventListener('touchmove', (evt) => {
this.handleTouchMove(evt)
}, false)
};
}
const swiper = new Swipe('#test')
swiper.onLeft(function () {
console.log('Hello world')
})
swiper.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment