-
-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathcopyable.js
More file actions
27 lines (26 loc) · 988 Bytes
/
copyable.js
File metadata and controls
27 lines (26 loc) · 988 Bytes
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
'use strict';
(() => {
function copyTextToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-1';
textArea.style.top = '-1';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
for (const block of document.getElementsByClassName('copyable')) {
const copyIcon = new Image(16, 16);
copyIcon.setAttribute('src', './assets/copy-icon.svg');
copyIcon.setAttribute('alt', 'copy');
copyIcon.setAttribute('title', 'copy to clipboard');
block.insertBefore(copyIcon, block.children[0]);
copyIcon.addEventListener('click', () => {
const text = block.getElementsByTagName('pre')[0].innerText;
copyTextToClipboard(text);
});
}
})();