-
Notifications
You must be signed in to change notification settings - Fork 922
/
Copy pathclick-to-copy.js
40 lines (33 loc) · 1.23 KB
/
click-to-copy.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
let codeListings = document.querySelectorAll(".highlight > pre");
for (let index = 0; index < codeListings.length; index++) {
const codeSample = codeListings[index].querySelector("code");
const copyButton = document.createElement("button");
const buttonAttributes = {
type: "button",
title: "Copy to clipboard",
"data-bs-toggle": "tooltip",
"data-bs-placement": "top",
"data-bs-container": "body",
};
Object.keys(buttonAttributes).forEach((key) => {
copyButton.setAttribute(key, buttonAttributes[key]);
});
copyButton.classList.add("fas", "fa-copy", "btn", "btn-dark", "btn-sm");
const tooltip = new bootstrap.Tooltip(copyButton);
copyButton.onclick = () => {
copyCode(codeSample);
copyButton.setAttribute("data-bs-original-title", "Copied!");
tooltip.show();
};
copyButton.onmouseout = () => {
copyButton.setAttribute("data-bs-original-title", "Copy to clipboard");
tooltip.hide();
};
const buttonDiv = document.createElement("div");
buttonDiv.classList.add("click-to-copy");
buttonDiv.append(copyButton);
codeListings[index].insertBefore(buttonDiv, codeSample);
}
const copyCode = (codeSample) => {
navigator.clipboard.writeText(codeSample.textContent.trim() + '\n');
};