DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

Copy text to the system clipboard on click with JavaScript

In this short tutorial I’ll be showing you how to add copy to clipboard functionality when a button is clicked using JavaScript. This comes in handy within web apps when you need to copy a large string of text or when using touch screen devices.

Let get started by setting up some HTML:

<input
  type="text"
  id="key-txt"
  value="1seWYeywqmTnqv7a5FC6LkD2vsdEx6jXOwqkmhLN"
  size="45"
  readonly
/>
<button id="key-btn">COPY</button>
Enter fullscreen mode Exit fullscreen mode

We can now begin the JavaScript functionality starting with declaring variables for the text and button element:

const keyTxt = document.getElementById("key-txt").value;
const keyBtn = document.getElementById("key-btn");
Enter fullscreen mode Exit fullscreen mode

Next we’ll add a click event listener to the button:

keyBtn.addEventListener("click", async () => {
  if (!navigator.clipboard) {
    alert("Copy functionality not supported");
  }
  try {
    await navigator.clipboard.writeText(keyTxt);
  } catch (err) {
    console.error("ERROR", err);
  }
});
Enter fullscreen mode Exit fullscreen mode

First we’re checking if the browser supports the navigator.clipboard which is part of the Clipboard API that provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the clipboard. If the browser does support navigator.clipboard the text is written to the clipboard.

That’s all for this tutorial, it should be noted that similar functionality could also be written using document.execCommand() however that method is no longer recommended as browsers drop support for it.

Top comments (1)

Collapse
 
diraskreact profile image
Dirask-React

It is good to look at legacy solution too: dirask.com/posts/JavaScript-how-to...