-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
56 lines (45 loc) · 1.68 KB
/
main.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const notificationTimeout = 2000
const copierStyle = `
cursor: pointer;
position: relative;
background: #000;
float: right;
border-radius: 5px;
color: #fff;
font-weight: bold;
padding: 4px;
font-size: 10px;
margin-right: 5px`;
const codeElements = ['code', 'samp'];
setTimeout(() => {
if (document.readyState !== 'loading') init()
else document.addEventListener('DOMContentLoaded', init);
}, 2500)
function init() {
let startIdx = 0;
codeElements.forEach((codeElement) => {
document.querySelectorAll(codeElement).forEach(ele => {
if (! validCodeElement(ele)) return;
ele.setAttribute('data-code-idx', startIdx);
ele.innerHTML += '<br>';
const copier = document.createElement('span');
copier.setAttribute('data-code-idx', startIdx);
copier.setAttribute('style', copierStyle);
copier.textContent = "Copy";
copier.addEventListener('click', copierClicked);
ele.parentElement.append(copier);
startIdx++;
})
})
}
function validCodeElement(ele) {
return ele.parentElement.tagName === 'PRE';
}
function copierClicked(e) {
const idx = e.target.getAttribute('data-code-idx');
if (! idx) return;
const value = document.querySelector('[data-code-idx="' + idx + '"]');
navigator.clipboard.writeText(value.textContent);
e.target.innerHTML = 'Copied <span style="color: #3d92ee">✔</span>';
setTimeout(() => e.target.textContent = "Copy", notificationTimeout);
}