1 // |
|
2 // Use LongPress() to set a function callback for a long-press on a particular DOM element. |
|
3 // Example: |
|
4 // <javascript ...> |
|
5 // new LongPress("btnId", function() { alert("hello"); }); |
|
6 // </javascript> |
|
7 // ... |
|
8 // <img id="btnId" ... /> |
|
9 // |
|
10 function LongPress(elementId, callback) { |
|
11 this.el = document.getElementById(elementId); |
|
12 this.callback = callback; |
|
13 this.initialX = 0; |
|
14 this.initialY = 0; |
|
15 |
|
16 if(!this.el) { |
|
17 window.chrome.alert("LongPress: element " + elementId + " not found"); |
|
18 return; |
|
19 } |
|
20 |
|
21 this.onTimerFired = function() { |
|
22 window.chrome.alert("onTimerFired"); |
|
23 this.callback.call(); |
|
24 this.cancelTimer(); |
|
25 this.unregisterMouseMove(); |
|
26 } |
|
27 |
|
28 this.startTimer = function() { |
|
29 this.cancelTimer(); |
|
30 this.timer = window.setTimeout(createDelegate(this, this.onTimerFired), 1500); |
|
31 } |
|
32 |
|
33 this.cancelTimer = function() { |
|
34 if(this.timer) { |
|
35 window.clearTimeout(this.timer); |
|
36 this.timer = null; |
|
37 } |
|
38 } |
|
39 |
|
40 // Stop tracking mouse movements. |
|
41 this.unregisterMouseMove= function() { |
|
42 this.el.onmousemove = null; |
|
43 } |
|
44 |
|
45 this.cancel = function() { |
|
46 window.chrome.alert("cancel"); |
|
47 this.cancelTimer(); |
|
48 this.unregisterMouseMove(); |
|
49 } |
|
50 |
|
51 // If the mouse has moved too much it's not considered a long press, so cancel. |
|
52 this.onMouseMove = function() { |
|
53 //window.chrome.alert("LongPress::onMouseMove " + this + " event=" + window.event + |
|
54 // " " + window.event.clientX + "," + window.event.clientY); |
|
55 if(Math.abs(this.initialX - window.event.clientX) > 4 || |
|
56 Math.abs(this.initialY - window.event.clientY) > 4) { |
|
57 this.cancel(); |
|
58 } |
|
59 } |
|
60 |
|
61 // Start tracking the mouse and save the initial mouse coords. |
|
62 this.onMouseDown = function() { |
|
63 window.chrome.alert("LongPress::onMouseDown " + this); |
|
64 this.isDown = true; |
|
65 this.initialX = window.event.clientX; |
|
66 this.initialY = window.event.clientY; |
|
67 this.el.onmousemove = this.onMouseMove.bind(this); |
|
68 this.startTimer(); |
|
69 } |
|
70 |
|
71 this.el.onmousedown = this.onMouseDown.bind(this); |
|
72 |
|
73 // Cancel tracking on mouse up and out events, ie. not a long press. |
|
74 this.el.onmouseup = this.cancel.bind(this); |
|
75 this.el.onmouseout = this.cancel.bind(this); |
|
76 } |
|