forked from madrobby/zepto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
touch.js
66 lines (58 loc) · 2.24 KB
/
touch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Zepto.js
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var touch = {}, touchTimeout
function parentIfText(node){
return 'tagName' in node ? node : node.parentNode
}
function swipeDirection(x1, x2, y1, y2){
var xDelta = Math.abs(x1 - x2), yDelta = Math.abs(y1 - y2)
return xDelta >= yDelta ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
var longTapDelay = 750, longTapTimeout
function longTap(){
longTapTimeout = null
if (touch.last && (Date.now() - touch.last >= longTapDelay)) {
touch.el.trigger('longTap')
touch = {}
}
}
$(document).ready(function(){
$(document.body).bind('touchstart', function(e){
var now = Date.now(), delta = now - (touch.last || now)
touch.el = $(parentIfText(e.touches[0].target))
touchTimeout && clearTimeout(touchTimeout)
touch.x1 = e.touches[0].pageX
touch.y1 = e.touches[0].pageY
if (delta > 0 && delta <= 250) touch.isDoubleTap = true
touch.last = now
longTapTimeout = setTimeout(longTap, longTapDelay)
}).bind('touchmove', function(e){
if (longTapTimeout) clearTimeout(longTapTimeout)
longTapTimeout = null
touch.x2 = e.touches[0].pageX
touch.y2 = e.touches[0].pageY
}).bind('touchend', function(e){
if (touch.isDoubleTap) {
touch.el.trigger('doubleTap')
touch = {}
} else if (touch.x2 > 0 || touch.y2 > 0) {
(Math.abs(touch.x1 - touch.x2) > 30 || Math.abs(touch.y1 - touch.y2) > 30) &&
touch.el.trigger('swipe') &&
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
touch.x1 = touch.x2 = touch.y1 = touch.y2 = touch.last = 0
} else if ('last' in touch) {
touch.el.trigger('tap')
touchTimeout = setTimeout(function(){
touchTimeout = null
touch.el.trigger('singleTap')
touch = {}
}, 250)
}
}).bind('touchcancel', function(){ touch = {} })
})
;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(m){
$.fn[m] = function(callback){ return this.bind(m, callback) }
})
})(Zepto)