Day 13: Copy to Clipboard
Build a copy-to-clipboard button that copies the current page URL (or other text), provides visual feedback when successful, and resets itself after a short delay.
JavaScript focus
- handling click events
- reading values from the DOM or window
- interacting with the clipboard
- updating UI state
- using setTimeout for temporary feedback
Nice extras
- copy the current page URL automatically
- add a small icon + text combo
- include accessible feedback (visually hidden text update)
- prevent repeated clicks while in “copied” state
- use a data attribute for the value to copy
MDN prep
Copy to Clipboard
The HTML
<section class="section copy_clipboard">
<h2 class="secondary_heading">Copy to Clipboard</h2>
<button type="button" class="button copy">Copy URL</button>
<div class="success-message" hidden>Copied to the clipboard!</div>
</section>
The JavaScript
async function writeClipboardText(text) {
try {
await navigator.clipboard.writeText(text);
} catch (error) {
console.error(error.message);
}
}
function initCopyToClipboard() {
const root = document.querySelector(".copy_clipboard");
if (!root) return;
const URL = window.location.href;
const button = root.querySelector(".copy");
const success = root.querySelector(".success-message");
button.addEventListener("click", () => {
writeClipboardText(URL);
button.setAttribute("disabled", "");
console.log("button disabled");
setTimeout(() => {
success.removeAttribute("hidden", "");
console.log("show success");
}, 500);
setTimeout(() => {
button.removeAttribute("disabled", "");
success.setAttribute("hidden", "");
console.log("enable button, remove success");
}, 5000);
return;
});
}
initCopyToClipboard();