JavaScript

Copy Text to Clipboard

by @admin
10h ago
Apr 28, 2026
Public
Copies a string to the system clipboard. Uses the modern navigator.clipboard.writeText API (requires HTTPS or localhost) and falls back to the deprecated document.execCommand approach for older browsers or non-secure contexts. Returns a Promise so you can show success/error feedback.
JavaScript
async function copyToClipboard(text) {
  if (navigator.clipboard?.writeText) {
    return navigator.clipboard.writeText(text);
  }
  // Fallback
  const el = Object.assign(document.createElement('textarea'), {
    value: text,
    style: 'position:fixed;opacity:0',
  });
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

// Usage
button.addEventListener('click', async () => {
  await copyToClipboard('Hello, world!');
  button.textContent = 'Copied!';
  setTimeout(() => (button.textContent = 'Copy'), 2000);
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.