-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdrags.js
75 lines (62 loc) · 2.01 KB
/
drags.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
var touchSupported = 'ontouchend' in document;
// Modified from http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
// so that we don't have an unnecessary dependency on jQuery UI
// However, this code is significantly less shitty
(function($) {
$.fn.drags = function(options) {
options = $.extend({
handle: null,
cursor: 'move',
draggingClass: 'dragging'
}, options);
var $handle = this,
$drag = this;
if( options.handle ) {
$handle = $(options.handle);
}
$handle
.css('cursor', options.cursor)
.on("mousedown", function(e) {
var x = $drag.offset().left - e.pageX,
y = $drag.offset().top - e.pageY;
$(document.documentElement)
.on('mousemove.drags', function(e) {
$drag.offset({
left: x + e.pageX,
top: y + e.pageY
});
})
.one('mouseup', function() {
$(this).off('mousemove.drags');
});
// disable selection
e.preventDefault();
});
if( touchSupported ) {
initTouchDrag($handle[0]);
}
};
})(jQuery);
// Make touch events work:
// http://stackoverflow.com/a/6362527/586086
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
// Clicks should continue to work
if( event.type === "touchmove" ) event.preventDefault();
}
function initTouchDrag(element) {
element.addEventListener("touchstart", touchHandler, true);
element.addEventListener("touchmove", touchHandler, true);
element.addEventListener("touchend", touchHandler, true);
element.addEventListener("touchcancel", touchHandler, true);
}