SyntaxStudy
Sign Up
HTML Beginner 3 min read

Clipboard API

Clipboard API

The modern Clipboard API provides async read/write access to the clipboard. Use it for "Copy to clipboard" buttons.

Example
<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>
Pro Tip

Clipboard API requires HTTPS and a user gesture — it will be blocked on HTTP.