javascript 40 lines · 8 steps

Copying to the clipboard with a fallback

A clipboard helper that tries the modern async API first, then quietly degrades to the legacy execCommand path.

Explained by highlit
1async function copyToClipboard(text) {
2 if (navigator.clipboard && window.isSecureContext) {
3 try {
4 await navigator.clipboard.writeText(text);
5 return true;
6 } catch (err) {
7 console.warn('Clipboard API failed, falling back:', err);
8 }
9 }
10 
11 const textarea = document.createElement('textarea');
12 textarea.value = text;
13 textarea.setAttribute('readonly', '');
14 textarea.style.position = 'fixed';
15 textarea.style.top = '-9999px';
16 textarea.style.opacity = '0';
17 document.body.appendChild(textarea);
18 
19 const selection = document.getSelection();
20 const savedRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
21 
22 textarea.select();
23 textarea.setSelectionRange(0, textarea.value.length);
24 
25 let succeeded = false;
26 try {
27 succeeded = document.execCommand('copy');
28 } catch (err) {
29 console.error('Fallback copy failed:', err);
30 }
31 
32 document.body.removeChild(textarea);
33 
34 if (savedRange) {
35 selection.removeAllRanges();
36 selection.addRange(savedRange);
37 }
38 
39 return succeeded;
40}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Feature-detect the modern API but always keep a working fallback for older or insecure contexts.
  2. 2The legacy copy path requires a real, selected DOM element, so build and clean up a hidden textarea.
  3. 3Restoring the user's prior selection keeps the copy operation invisible and non-disruptive.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Copying to the clipboard with a fallback — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code