-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy-text.js
35 lines (31 loc) · 1.02 KB
/
copy-text.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
function temporarilySwapClass(node, { from, to }) {
node.classList.remove(from);
node.classList.add(to);
setTimeout(() => {
node.classList.remove(to);
node.classList.add(from);
}, 750);
}
function temporarilyApplyClass(node, className) {
node.classList.add(className);
setTimeout(() => {
node.classList.remove(className);
}, 750);
}
export function copyText(text, button, icon) {
navigator.clipboard.writeText(text)
.then(() => {
temporarilyApplyClass(button, 'copy-success');
temporarilySwapClass(icon, { from: 'bi-copy', to: 'bi-clipboard-check-fill' });
})
.catch(() => {
temporarilyApplyClass(button, 'copy-failure');
temporarilySwapClass(icon, { from: 'bi-copy', to: 'bi-clipboard-x-fill' });
const textNode = button.parentElement.querySelector('span');
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(textNode);
selection.removeAllRanges();
selection.addRange(range);
});
}