DEV Community

WDSEGA
WDSEGA

Posted on • Originally published at wdsega.github.io

Component Deep Dive #21: Copy to Clipboard - 3 Lines of Modern JS, Zero Excuses

Web Component Dictionary v2.0 - 83 Components / 8 Categories / Bilingual / Live Preview
Live Demo | Buy

The code copy button on docs pages reduces user errors by 99%. Here is the complete implementation.

The Core API

async function copyToClipboard(text) {
  await navigator.clipboard.writeText(text);
}
Enter fullscreen mode Exit fullscreen mode

Visual Feedback

btn.classList.add('copied');
copyText.textContent = 'Copied!';
setTimeout(() => {
  btn.classList.remove('copied');
  copyText.textContent = 'Copy';
}, 2000);
Enter fullscreen mode Exit fullscreen mode

Old Browser Fallback

const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
Enter fullscreen mode Exit fullscreen mode

Critical Rules

  1. HTTPS only - Clipboard API is unavailable on plain HTTP
  2. Always use await - without it, success feedback fires before copy completes
  3. Store copy content in data-copy attribute for zero-coupling declarative markup

Full code and bilingual article

Top comments (0)