#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Copy text to the system clipboard on click with JavaScript

Last modified June 21st 2021 | GitHub Source Code [GitHub] | #js

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:

<button id="key-btn">COPY</button>Code language: HTML, XML (xml)

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");Code language: JavaScript (javascript)

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);
});Code language: JavaScript (javascript)

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.

Related Posts

#AD Shop Web Developer T-Shirts