Back to all snippets
Library/Tailwind CSS/Copy to Clipboard (Modern API)
htmlbeginnerjavascriptclipboardapiux

How to implement Copy to Clipboard (Modern API) in Html

Copy text to clipboard using the modern Clipboard API

Quick Answer

Use `navigator.clipboard.writeText()` to copy — it's cleaner than the old `document.execCommand('copy')`. Always include a fallback for older browsers and show user feedback.

Code Snippet

1<!-- Copy button with feedback -->
2<div class="flex items-center gap-2">
3  <code class="flex-1 bg-gray-100 text-gray-900 px-3 py-2 rounded text-sm">npm install @package/name</code>
4  <button id="copyBtn" class="px-3 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition-colors" title="Copy to clipboard">
5    Copy
6  </button>
7</div>
8
9<script>
10  const copyBtn = document.getElementById('copyBtn');
11  const textToCopy = copyBtn.parentElement.querySelector('code').textContent;
12
13  copyBtn.addEventListener('click', async () => {
14    try {
15      // Modern Clipboard API
16      await navigator.clipboard.writeText(textToCopy);
17      
18      // Show feedback
19      const originalText = copyBtn.textContent;
20      copyBtn.textContent = 'Copied!';
21      copyBtn.classList.add('bg-green-600');
22      copyBtn.classList.remove('bg-indigo-600');
23      
24      setTimeout(() => {
25        copyBtn.textContent = originalText;
26        copyBtn.classList.remove('bg-green-600');
27        copyBtn.classList.add('bg-indigo-600');
28      }, 2000);
29    } catch (err) {
30      // Fallback for older browsers
31      try {
32        const textarea = document.createElement('textarea');
33        textarea.value = textToCopy;
34        document.body.appendChild(textarea);
35        textarea.select();
36        document.execCommand('copy');
37        document.body.removeChild(textarea);
38        
39        copyBtn.textContent = 'Copied!';
40        setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000);
41      } catch (fallbackErr) {
42        console.error('Copy failed:', fallbackErr);
43      }
44    }
45  });
46</script>

What is Copy to Clipboard (Modern API)?

The old way to copy to clipboard (`document.execCommand('copy')`) is deprecated and unreliable. The modern Clipboard API (`navigator.clipboard.writeText()`) is cleaner, more predictable, and is now supported in all modern browsers. This snippet includes a fallback for older browsers and shows best practices for user feedback.

How It Works

  1. 1`navigator.clipboard.writeText(text)` is the modern, async Clipboard API
  2. 2Returns a Promise — use `.then()` or `await` to handle success
  3. 3Falls back to `document.execCommand('copy')` for older browsers (IE, Edge < 79)
  4. 4Show visual feedback (tooltip or class toggle) so users know the copy succeeded

Common Use Cases

  • Code snippets - Let users copy code examples with one click
  • Share links - Copy a shortened URL to clipboard
  • API keys - Copy authentication tokens or API credentials
  • Any text - Generic copy-to-clipboard for any text content

Key Benefits

  • Modern API is cleaner than the deprecated execCommand
  • Async operation integrates well with modern JavaScript
  • Better browser support in 2024+
  • Fallback for older environments

Common Mistakes to Avoid

  • Not handling the error case — `writeText` can reject if the user denies clipboard permission. Always add `.catch()`.
  • Relying only on Clipboard API without fallback — some browsers and environments (sandboxed iframes) don't support it.
  • Not providing user feedback — users expect visual confirmation that the copy succeeded (tooltip, toast, or button state change).

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more html examples

Frequently Asked Questions

Can I copy formatted text (HTML) to the clipboard?

Yes, using `navigator.clipboard.write()` with multiple MIME types. But most destinations (Google Docs, Word, etc.) accept only plain text from the browser for security. For Markdown or code, copy as plain text.

Do I need user permission to use the Clipboard API?

Yes, in HTTPS contexts. HTTP contexts are blocked unless the page is a localhost development server. Clipboard API access is considered a sensitive permission by browsers.

About This Html Code Snippet

This free html code snippet for copy to clipboard (modern api) is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement copy to clipboard (modern api) quickly and correctly.

All snippets in the Snippetly library follow html best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses html.

Tags: javascript, clipboard, api, ux  | Language: html  | Difficulty: beginner  | Category: Tailwind CSS

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.