-
Notifications
You must be signed in to change notification settings - Fork 1
/
clipboard.js
40 lines (31 loc) · 1.04 KB
/
clipboard.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
function clipboard(selectors, options, callback) {
let defaultOptions = {
position: 'beforebegin',
template: '<div class="clipboard"><button class="clipboard-button" type="button">Copy</button></div>'
};
options = {
...defaultOptions,
...options
};
document.querySelectorAll(selectors).forEach(function (element) {
let template = document.createElement('template');
template.insertAdjacentHTML('afterbegin', options.template);
let clipboard = template.firstChild;
element.insertAdjacentElement(options.position, clipboard);
clipboard.addEventListener('click', function() {
let text = element.innerText;
if (text.length == 0) {
text = element.value;
}
let textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.value = text;
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
});
if (typeof callback == 'function') {
callback(clipboard, element);
}
});
}