swipe event
by Amine Tbaik
HTML
<div></div>
CSS
div{
background: lightblue;
width: 100px;
height: 100px;
}
JavaScript
$.fn.swipe = function(f) {
this.on('swipe', function(e, p) {
f.call(this, p)
})
let touchstart = false,
touchmove = false,
init = {}
$(this).on('touchstart', function(e) {
touchstart = true
init.x = e.pageX
init.y = e.pageY
init.t = e.timeStamp
}).on('touchmove', function() {
if (touchstart) {
touchstart = false
touchmove = true
}
}).on('touchend', function(e) {
if (touchmove) {
touchmove = false
let final = {
x: e.pageX,
y: e.pageY,
t: e.timeStamp
}
let d = {
x: final.x - init.x,
y: final.y - init.y,
t: final.t - init.t
}
let axis = Math.abs(d.x) > Math.abs(d.y) ? 'h' : 'v'
if (axis == 'h' && d.x > 0) {
e.direction = 'right'
} else if (axis == 'h' && d.x < 0) {
e.direction = 'left'
} else if (axis == 'v' && d.y > 0) {
e.direction = 'down'
} else if (axis == 'v' && d.y < 0) {
e.direction = 'up'
} else {
e.direction = null
}
$(this).trigger('swipe', e)
}
})
return this
}