Clipboard API
The modern Clipboard API provides async read/write access to the clipboard. Use it for "Copy to clipboard" buttons.
The modern Clipboard API provides async read/write access to the clipboard. Use it for "Copy to clipboard" buttons.
<input id="code" value="npm install my-package" readonly>
<button onclick="copyCode()">Copy</button>
<span id="msg"></span>
<script>
async function copyCode() {
const text = document.getElementById("code").value;
try {
await navigator.clipboard.writeText(text);
document.getElementById("msg").textContent = "Copied!";
setTimeout(() => document.getElementById("msg").textContent = "", 2000);
} catch (err) {
console.error("Copy failed:", err);
}
}
</script>
Clipboard API requires HTTPS and a user gesture — it will be blocked on HTTP.