-
Notifications
You must be signed in to change notification settings - Fork 11
/
gotem.js
39 lines (32 loc) · 1.14 KB
/
gotem.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
const gotem = (trigger, target, cbs = {}) => {
// throw if no target node or no trigger node
if (trigger.nodeType !== window.Node.ELEMENT_NODE || target.nodeType !== window.Node.ELEMENT_NODE) {
throw new Error('gotem: trigger and target nodes are required.')
}
const handle = event => {
// prevent default link behavior
// note that tagName returns in uppercase
if (trigger.tagName === 'A') {
event.preventDefault()
}
// create range, and select target node contents
const range = document.createRange()
range.selectNodeContents(target)
// remove existing selections, then add the new one
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
// execute the copy command
const executed = document.execCommand('copy')
// based on if the command executed
// check if the appropriate callback exists, and if it does, call it
if (executed) {
cbs.success && cbs.success()
} else {
cbs.error && cbs.error()
}
}
// bind the click handler to the trigger node
trigger.addEventListener('click', handle)
}
export default gotem