forked from feross/drag-drop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (35 loc) · 1.03 KB
/
index.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
module.exports = DragDrop
var throttle = require('lodash.throttle')
function DragDrop (elem, cb) {
if (typeof elem === 'string') elem = document.querySelector(elem)
elem.addEventListener('dragenter', killEvent, false)
elem.addEventListener('dragover', makeOnDragOver(elem), false)
elem.addEventListener('drop', onDrop.bind(undefined, elem, cb), false)
}
function killEvent (e) {
e.stopPropagation()
e.preventDefault()
return false
}
function makeOnDragOver (elem) {
var fn = throttle(function () {
elem.classList.add('drag')
if (elem.timeout) clearTimeout(elem.timeout)
elem.timeout = setTimeout(function () {
elem.classList.remove('drag')
}, 150)
}, 100, {trailing: false})
return function (e) {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
fn()
}
}
function onDrop (elem, cb, e) {
e.stopPropagation()
e.preventDefault()
elem.classList.remove('drag')
cb(Array.prototype.slice.call(e.dataTransfer.files), { x: e.clientX, y: e.clientY })
return false
}