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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Feature-detect the modern API but always keep a working fallback for older or insecure contexts.
- 2The legacy copy path requires a real, selected DOM element, so build and clean up a hidden textarea.
- 3Restoring the user's prior selection keeps the copy operation invisible and non-disruptive.
Related explainers
rust
use std::time::Duration; use tokio::time::sleep; #[derive(Debug)]
Async retry with exponential backoff in Rust
retry
exponential-backoff
async
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from "react"; export function Dropdown({ label, children }) { const [open, setOpen] = useState(false);
Closing a dropdown on outside click in React
outside-click
event-listeners
cleanup
Intermediate
8 steps
go
package server import ( "net/http"
Serving a single-page app with Gin
static-files
spa
routing
Intermediate
7 steps
rust
use std::fs; use std::io; use std::path::{Path, PathBuf};
Recursive file search by extension in Rust
recursion
filesystem
error-handling
Intermediate
8 steps
typescript
type Ok<T> = { ok: true; value: T }; type Err<E> = { ok: false; error: E }; export type Result<T, E> = Ok<T> | Err<E>;
A Result type for typed error handling
discriminated-union
error-handling
type-guards
Intermediate
8 steps
javascript
'use server' import { z } from 'zod' import { redirect } from 'next/navigation'
How a Next.js Server Action validates a form
server-actions
form-validation
zod
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/copying-to-the-clipboard-with-a-fallback-explained-javascript-dcf0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.