Free Web & Developer Tools

Fast, lightweight, and built to solve daily coding and blogging tasks.

Explore All Tools

How to Build a Zero-Dependency Copy to Clipboard in JavaScript

A copy button saves readers from selecting text by hand, which is slow on a phone and easy to get wrong with code. Libraries like clipboard.js exist for this, but the browser already has what you need, and the finished script below is about 120 lines, comments included, with no dependencies.

This guide starts with the shortest working version, shows where it breaks, and builds up to a script that copies from data attributes, falls back for older browsers and insecure pages, reports success to screen readers, and can add a copy button to every code block on a page.

The simplest version

The Clipboard API has one method for plain text, navigator.clipboard.writeText(). It returns a promise.

button.addEventListener("click", async () => {
  await navigator.clipboard.writeText("Text to copy");
  button.textContent = "Copied!";
});

That works on a page served over HTTPS in a current browser. It fails quietly in several other situations.

Situation What happens How the final script handles it
The page is served over plain HTTP, other than localhost navigator.clipboard is undefined, so the call throws a TypeError. Checks for the API first and falls back to the legacy method.
The document is not focused, or the call is not tied to a user action The promise rejects with NotAllowedError. Catches the rejection and tries the fallback.
The page is inside an iframe without clipboard permission The promise rejects. Falls back, and shows "Copy failed" if that fails too. The embedding page needs allow="clipboard-write" on the iframe.
An older browser or in-app web view The API is missing. Uses the legacy method.
The copy fails for any reason The button still says "Copied!". Reports success or failure from the real result.
The user clicks twice quickly The label can get stuck on "Copied!" or reset too early. Stores the original label once and restarts the timer on every click.
The user relies on a screen reader A button label change is often not announced. Updates a hidden live region.

Three ways to write to the clipboard

Method Status Works on plain HTTP Best for
navigator.clipboard.writeText() Current standard No, secure contexts only Plain text. Use this first.
document.execCommand("copy") Deprecated, but still works in the major browsers Yes A fallback when the Clipboard API is unavailable.
navigator.clipboard.write() with ClipboardItem Current standard, support varies by browser No, secure contexts only HTML and images. Check support before relying on it.

A copy function with a fallback

copyText() tries the modern API and falls back to legacyCopy(). It resolves to true or false, so the caller can show the real outcome.

async function copyText(text) {
  // Modern API: needs HTTPS (or localhost) and a user gesture.
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch {
      // Permission denied, document not focused, or no user gesture.
      // Fall through to the legacy method.
    }
  }
  return legacyCopy(text);
}

function legacyCopy(text) {
  const previousFocus = document.activeElement;
  const selection = document.getSelection();
  const previousRange =
    selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.setAttribute("readonly", ""); // keeps the mobile keyboard closed
  textarea.style.cssText = "position:fixed;top:0;left:0;opacity:0;pointer-events:none;";
  document.body.append(textarea);
  textarea.select();
  textarea.setSelectionRange(0, text.length); // needed on iOS

  let copied = false;
  try {
    copied = document.execCommand("copy");
  } catch {}

  textarea.remove();

  // Put the user's focus and selection back where they were.
  if (previousRange) {
    selection.removeAllRanges();
    selection.addRange(previousRange);
  }
  previousFocus?.focus?.({ preventScroll: true });

  return copied;
}

What the functions do

  • copyText() is an async function, so callers use await and get a plain boolean. JavaScript promises and async/await explained covers how that works if you want a refresher.
  • The modern path runs only when navigator.clipboard exists and window.isSecureContext is true.
  • The fallback copies through a temporary <textarea>, because execCommand("copy") works on a selection. The textarea is read-only so phones do not open the keyboard, and it is fixed and transparent so the page does not jump or flicker.
  • setSelectionRange() is there for iOS, where select() alone does not always select the text.
  • After the fallback, the user's previous focus and text selection are restored. Without this, a keyboard user who pressed the button would lose their place on the page.

Wire up buttons with data attributes

Instead of writing a click handler for every button, describe what to copy in the HTML. A single listener on the document finds the right button, so buttons added later work too.

<!-- Copy a fixed string -->
<button type="button" data-copy-text="npm install my-package">Copy</button>

<!-- Copy the text of another element -->
<code id="install">npm install my-package</code>
<button type="button" data-copy-target="#install">Copy</button>

<!-- Copy the value of an input -->
<input id="share-link" value="https://example.com/post" readonly>
<button type="button" data-copy-target="#share-link">Copy link</button>

Add the script that handles the clicks:

function initCopyButtons({ resetAfter = 2000 } = {}) {
  const timers = new WeakMap();

  // One hidden live region announces the result to screen readers.
  const live = document.createElement("div");
  live.setAttribute("role", "status");
  live.style.cssText =
    "position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;";
  document.body.append(live);

  function getText(button) {
    if (button.dataset.copyText !== undefined) return button.dataset.copyText;

    let source = null;
    try {
      source = document.querySelector(button.dataset.copyTarget);
    } catch {} // invalid selector
    if (!source) return null;

    const isField =
      source instanceof HTMLInputElement || source instanceof HTMLTextAreaElement;
    return isField ? source.value : source.textContent;
  }

  function report(button, message) {
    if (button.dataset.copyLabel === undefined) {
      button.dataset.copyLabel = button.textContent; // remember the original label once
    }
    clearTimeout(timers.get(button));
    button.textContent = message;
    live.textContent = message;

    timers.set(
      button,
      setTimeout(() => {
        button.textContent = button.dataset.copyLabel;
        live.textContent = "";
      }, resetAfter)
    );
  }

  // One listener handles every copy button, including ones added later.
  document.addEventListener("click", async (event) => {
    const button = event.target.closest("[data-copy-text], [data-copy-target]");
    if (!button) return;

    const text = getText(button);
    if (text === null) {
      console.warn("Copy button has no valid source:", button);
      return;
    }

    report(button, (await copyText(text)) ? "Copied!" : "Copy failed");
  });
}

How it reads the text

  • data-copy-text copies a fixed string.
  • data-copy-target takes a CSS selector. Inputs and textareas are read through .value. Everything else is read through textContent, which keeps line breaks and indentation in code. innerText depends on layout and can change whitespace, so it is the wrong choice for code.
  • A missing or invalid selector logs a warning and does nothing, instead of throwing.
  • An empty string counts as valid text.

How it reports the result

  • The button label changes to "Copied!" or "Copy failed" and returns to the original after two seconds. Change the delay with initCopyButtons({ resetAfter: 3000 }).
  • The original label is saved on the first click, so repeated clicks never leave the button stuck on the wrong text.
  • The same message goes into a visually hidden element with role="status", which screen readers announce. The element is created when the script starts, because browsers only announce changes to a live region that already exists.

Add copy buttons to code blocks automatically

For a blog or a documentation page, you can add a button to every <pre> block without touching the HTML of each post.

let copySourceCount = 0;

function addCopyButtons(selector = "pre") {
  document.querySelectorAll(selector).forEach((pre) => {
    if (pre.parentElement?.classList.contains("code-block")) return; // already done

    const source = pre.querySelector("code") || pre;
    if (!source.id) source.id = `copy-source-${++copySourceCount}`;

    const button = document.createElement("button");
    button.type = "button";
    button.className = "copy-btn";
    button.textContent = "Copy";
    button.setAttribute("aria-label", "Copy code to clipboard");
    button.dataset.copyTarget = `#${source.id}`;

    // The button sits next to the <pre>, not inside it,
    // so its label never ends up in the copied text.
    const wrapper = document.createElement("div");
    wrapper.className = "code-block";
    pre.replaceWith(wrapper);
    wrapper.append(pre, button);
  });
}

Each button points at the <code> element inside its block, or at the block itself when there is no <code>. Elements without an id get a generated one. The function skips blocks it has already wrapped, so calling it twice is safe.

The button goes into a wrapper next to the <pre> rather than inside it. A button inside the block would add its own label to the copied text.

Position the button with a little CSS:

.code-block {
  position: relative;
}

.copy-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 10px;
  font: inherit;
  font-size: 0.8rem;
  cursor: pointer;
}

Run both functions after the page has loaded. Put the script at the end of <body> or load it with defer:

initCopyButtons();
addCopyButtons();
Info! On a Blogger blog, paste the script into Theme, then Edit HTML, just before </body>. The editor reads the theme as XML, so characters such as && and < can cause a parse error. Wrap the script in //<![CDATA[ and //]]> to avoid it. If the Edit HTML screen is new to you, how to install a Blogger template properly shows how the Theme screen works.

Accessibility checklist

  • Use a real <button type="button">. It works with Enter and Space and exposes the right role without extra code.
  • Keep the visible word in the accessible name. The generated buttons show "Copy" and have the label "Copy code to clipboard", which contains it.
  • Announce the result through the live region, not only through the button text.
  • State the result in words. A color change or an icon alone does not reach every user.
  • Keep focus on the button after copying. The fallback restores it for you.
Warning! Copy only in response to a click or key press that the user expects. Writing to the clipboard on page load, on a timer or inside an unrelated event is hostile behavior, and browsers block it. Be careful with sensitive values such as passwords or tokens too. Other apps and clipboard managers can read whatever you copy.

Test it

  1. Save your page and the script, then serve the folder over localhost, which counts as a secure context. For example, run python3 -m http.server 8000 in the folder and open http://localhost:8000.
  2. Click a copy button. The label changes to "Copied!" and goes back after two seconds.
  3. Paste into a text field. The pasted text should match the source exactly, including line breaks in code.
  4. Click the button three times in a row. The label should still return to the original wording.
  5. Tab to a button and press Enter or Space. It should copy, and focus should stay on the button.
  6. To test the fallback, open the page from your computer's local network address over plain HTTP, for example http://192.168.1.20:8000 on a phone. There navigator.clipboard is undefined, so the legacy path runs.
Done! If the text pastes correctly over both localhost and plain HTTP, both code paths work.

Troubleshooting

Cannot read properties of undefined (reading 'writeText')

Error! navigator.clipboard is undefined, usually because the page is served over plain HTTP.

Serve the site over HTTPS, test on localhost, or use the script above, which checks for the API before calling it. How to read error messages like a developer explains how to read messages like this one.

NotAllowedError: Write permission denied or Document is not focused

The browser refused the write. Make sure the copy runs inside a click or key handler and that the page has focus. Inside an iframe, the embedding page must include allow="clipboard-write". The script falls back to the legacy method for these cases, and shows "Copy failed" if that fails too.

It works on desktop but not on iPhone

Safari is stricter about user activation. Avoid slow work between the tap and the copy, such as a network request, because the permission can expire. Prepare the text before the click. The fallback already uses a read-only textarea and setSelectionRange(), which iOS needs.

The copied code includes the word "Copy"

The button is inside the element being copied. Keep it outside the <pre>, as addCopyButtons() does, or copy from the inner <code> element.

Line breaks or indentation are lost

The text was read with innerText, or the element had its whitespace collapsed by CSS. Read code with textContent, as the script does.

FAQs

How do I copy text to the clipboard in JavaScript?

Call navigator.clipboard.writeText("your text") inside a click handler. It returns a promise that resolves when the text is copied and rejects if the browser refuses. The page must be served over HTTPS or from localhost.

Why is navigator.clipboard undefined?

The Clipboard API is only available in secure contexts. A page loaded over plain HTTP, from anywhere other than localhost, does not get it. Serve the page over HTTPS, or fall back to document.execCommand("copy").

Is document.execCommand("copy") still safe to use?

It is deprecated, but the major browsers still support it, so it works as a fallback. Do not build new features on it. Keep it behind a check for the modern API, as the script in this guide does.

Can I copy to the clipboard without a click?

In practice, no. Browsers require a user action such as a click or key press before a page can write to the clipboard, which stops sites from replacing what the user copied without them noticing.

How do I copy images or formatted HTML?

writeText() handles plain text only. For images or HTML, use navigator.clipboard.write() with a ClipboardItem. Support differs between browsers and the allowed formats are limited, so check current browser compatibility before you depend on it.

Conclusion

A reliable copy button needs more than one line. Use navigator.clipboard.writeText() first, fall back to a temporary textarea for plain HTTP and older browsers, report the real result, and announce it to screen readers. Read code with textContent, keep the button outside the text being copied, and write to the clipboard only when the user asks.

About the author

Suptojit Modak
Suptojit Modak
I'm Suptojit Modak, a web developer and the person behind BytebaseX — a blog with tutorials, guides, and free resources for developers and bloggers, built to be simple and easy to follow.

Instagram · GitHub · Facebook

Post a Comment