JavaScript Copy Text to Clipboard

You can copy text to the visitor’s clipboard with the modern Clipboard API. It is used for “Copy code” and “Copy link” buttons.

HTML and JavaScript

<input type="text" id="coupon" value="SAVE20" readonly>
<button id="copyBtn">Copy</button>
<span id="status"></span>

<script>
  const input = document.getElementById("coupon");
  const status = document.getElementById("status");

  document.getElementById("copyBtn").addEventListener("click", async () => {
    try {
      await navigator.clipboard.writeText(input.value);
      status.textContent = "Copied!";
    } catch (error) {
      status.textContent = "Could not copy";
    }
  });
</script>

Output in the browser (after clicking Copy):

Output in the browser

Copied!

How it works

  • navigator.clipboard.writeText() returns a promise, so we use await (see async and await).
  • It works only on secure pages (https or localhost) and after a user action like a click.
  • The try...catch shows a message if the browser blocks it.

To read text from the clipboard use navigator.clipboard.readText(). The browser asks the visitor for permission first.


Learn more about the similar topics:
Tutorials
JavaScript Events
JavaScript HTML DOM
JavaScript DOM Manipulation
JavaScript HTML DOM EventListener
JavaScript Forms and Validation
Exercises & Assignments
Write a JavaScript program to change the text of a paragraph on button click
Write a JavaScript program to switch dark mode on and off
Interview Questions & Answers
What is the DOM in JavaScript?
How do you select elements in the DOM?
What are events and event listeners in JavaScript?
What is event bubbling and capturing in JavaScript?
What is event delegation in JavaScript?