forked from vaidik/jquery-longpress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.longpress.js
79 lines (69 loc) · 2.75 KB
/
jquery.longpress.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
/**
* Longpress is a jQuery plugin that makes it easy to support long press
* events on mobile devices and desktop borwsers.
*
* @name longpress
* @version 0.1.2
* @requires jQuery v1.2.3+
* @author Vaidik Kapoor
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, check out the README at:
* http://github.com/vaidik/jquery-longpress/
*
* Copyright (c) 2008-2013, Vaidik Kapoor (kapoor [*dot*] vaidik -[at]- gmail [*dot*] com)
*/
(function($) {
$.fn.longpress = function(longCallback, shortCallback, duration) {
if (typeof duration === "undefined") {
duration = 500;
}
return this.each(function() {
var $this = $(this);
// to keep track of how long something was pressed
var mouse_down_time;
var timeout;
// mousedown or touchstart callback
function mousedown_callback(e) {
mouse_down_time = new Date().getTime();
var context = $(this);
// set a timeout to call the longpress callback when time elapses
timeout = setTimeout(function() {
if (typeof longCallback === "function") {
longCallback.call(context, e);
} else {
$.error('Callback required for long press. You provided: ' + typeof longCallback);
}
}, duration);
}
// mouseup or touchend callback
function mouseup_callback(e) {
var press_time = new Date().getTime() - mouse_down_time;
if (press_time < duration) {
// cancel the timeout
clearTimeout(timeout);
// call the shortCallback if provided
if (typeof shortCallback === "function") {
shortCallback.call($(this), e);
} else if (typeof shortCallback === "undefined") {
;
} else {
$.error('Optional callback for short press should be a function.');
}
}
}
// cancel long press event if the finger or mouse was moved
function move_callback(e) {
clearTimeout(timeout);
}
// Browser Support
$this.on('mousedown', mousedown_callback);
$this.on('mouseup', mouseup_callback);
$this.on('mousemove', move_callback);
// Mobile Support
$this.on('touchstart', mousedown_callback);
$this.on('touchend', mouseup_callback);
$this.on('touchmove', move_callback);
});
};
}(jQuery));