DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

6 2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
diraskreact profile image
Dirask-React

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay