Skip to content

Instantly share code, notes, and snippets.

@tfsojon
Created March 1, 2023 09:51
Show Gist options
  • Save tfsojon/10e324240ff013658d2bbd37d3d8a508 to your computer and use it in GitHub Desktop.
Save tfsojon/10e324240ff013658d2bbd37d3d8a508 to your computer and use it in GitHub Desktop.
let blocks = document.querySelectorAll("pre");
blocks.forEach((block) => {
if (navigator.clipboard) {
let button = document.createElement("button");
button.innerText = "copy";
button.className = "copy-to-clipboard";
block.appendChild(button);
button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});
async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
button.innerText = "copied";
setTimeout(() => {
button.innerText = "copy";
}, 700);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment