forked from cargomedia/jquery.touchToClick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.touchToClick.js
97 lines (83 loc) · 2.21 KB
/
jquery.touchToClick.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* Author: cargomedia.ch
*
* Binds 'touchstart' when binding $.on('click')
* and triggers 'click' when 'touchend' happens without 'touchmove' inbetween.
*/
(function($) {
if (!("ontouchstart" in window)) {
return;
}
var clickbuster = {
isLocked: false,
delayedUnlock: null,
onClick: function(event) {
if (this.isLocked) {
event.stopPropagation();
event.preventDefault();
}
},
lock: function() {
this.isLocked = true;
var clickbuster = this;
this.delayedUnlock = setTimeout(function() {
clickbuster.unlock();
}, 2000);
},
unlock: function() {
this.isLocked = false;
if (this.delayedUnlock) {
window.clearTimeout(this.delayedUnlock);
}
}
};
document.addEventListener('click', function(e) {
clickbuster.onClick(e);
}, true);
$.event.special.click = {
delegateType: "click",
bindType: "click",
setup: function(data, namespaces, eventHandle) {
var element = this;
var touchHandler = {
handleEvent: function(e) {
switch(e.type) {
case 'touchstart': this.onTouchStart(e); break;
case 'touchmove': this.onTouchMove(e); break;
case 'touchend': this.onTouchEnd(e); break;
}
},
onTouchStart: function(e) {
e.stopPropagation();
this.moved = false;
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
onTouchMove: function(e) {
this.moved = true;
},
onTouchEnd: function(e) {
element.removeEventListener('touchmove', this, false);
element.removeEventListener('touchend', this, false);
if (!this.moved) {
clickbuster.unlock();
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
e.target.dispatchEvent(theEvent);
clickbuster.lock();
e.stopPropagation();
}
}
};
element.addEventListener('touchstart', touchHandler, false);
$(element).data('touchToClick-handler', touchHandler);
return false;
},
teardown: function(namespaces) {
var element = this;
var touchHandler = $(element).data('touchToClick-handler');
element.removeEventListener('touchstart', touchHandler, false);
return false;
}
};
})(jQuery);