const copyButtonLabel = "Copy Code"; // use a class selector if available if (navigator.clipboard) { let blocks = document.querySelectorAll("pre"); blocks.forEach((block) => { // only add button if browser supports Clipboard API let button = document.createElement("button"); button.innerText = copyButtonLabel; block.parentNode.insertBefore(button, block); button.addEventListener("click", async (event) => { await copyCode(block, event.target); }); }); } 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); }