Copy Text to the Clipboard with JavaScript

Last updated: August 29, 2026.

The Clipboard API works in secure contexts and normally requires a user action. Attach it to a real button and handle permission or browser failures.

Copy from a code block

const button = document.querySelector('#copy');
const source = document.querySelector('#code');
const status = document.querySelector('#copy-status');

button.addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText(source.textContent);
    status.textContent = 'Copied';
  } catch (error) {
    status.textContent = 'Copy failed. Select the text and copy it manually.';
  }
});

Make feedback accessible

  • Use a button, not a clickable div.
  • Place status text in an aria-live region.
  • Do not copy without an explicit user action.
  • Provide manual selection as a fallback.

Treat copying as an explicit action

Clipboard access normally requires HTTPS and a user gesture. Use a real button, report success in an aria-live region, and provide a manual selection fallback when permission is denied.

Test browsers with blocked clipboard permission, keyboard activation, and text containing line breaks or non-ASCII characters. Copy textContent when markup should not be included.

  • Do not copy automatically on page load.
  • Keep the status message brief.
  • Reset success feedback after a short interval.

Progressive enhancement matters: preserve semantic HTML and a usable server-side path. Test keyboard operation, failure states, and rapid repeated actions rather than only the ideal mouse interaction.

Continue with HTML entities and Unicode code points.

Practical implementation check

Keep the underlying HTML usable before JavaScript runs, then add behavior as an enhancement. Test rapid repeated interaction, keyboard use, a slow or failed network request, and navigation away from the page. Remove temporary listeners or resources when appropriate, and ensure visible status changes are also available to assistive technology.

Keep the event handler small and move reusable work into a named function. That makes cleanup, error handling, and isolated testing easier as the interface gains more states.

Reference: MDN Clipboard writeText reference.

admin

admin