2024-04-23 08:12:30 -04:00
|
|
|
const copyButtonLabel = "Copy Code";
|
|
|
|
|
|
|
|
// use a class selector if available
|
2024-04-23 08:44:25 -04:00
|
|
|
if (navigator.clipboard) {
|
|
|
|
let blocks = document.querySelectorAll("pre");
|
2024-04-23 08:12:30 -04:00
|
|
|
|
2024-04-23 08:44:25 -04:00
|
|
|
blocks.forEach((block) => {
|
|
|
|
// only add button if browser supports Clipboard API
|
|
|
|
let button = document.createElement("button");
|
2024-04-23 08:12:30 -04:00
|
|
|
|
2024-04-23 08:44:25 -04:00
|
|
|
button.innerText = copyButtonLabel;
|
|
|
|
block.parentNode.insertBefore(button, block);
|
2024-04-23 08:12:30 -04:00
|
|
|
|
2024-04-23 08:44:25 -04:00
|
|
|
button.addEventListener("click", async (event) => {
|
|
|
|
await copyCode(block, event.target);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2024-04-23 08:12:30 -04:00
|
|
|
|
|
|
|
async function copyCode(block, button) {
|
|
|
|
let code = block.querySelector("code");
|
|
|
|
let text = code.innerText;
|
|
|
|
|
|
|
|
await navigator.clipboard.writeText(text);
|
|
|
|
|
|
|
|
// visual feedback that task is completed
|
|
|
|
button.innerText = "Code Copied";
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
button.innerText = copyButtonLabel;
|
|
|
|
}, 700);
|
|
|
|
}
|