Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 29, 2021 11:19 pm GMT

Copy text to the system clipboard on click with JavaScript

In this short tutorial Ill 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>

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");

Next well 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);  }});

First were 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.

Thats 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.


Original Link: https://dev.to/michaelburrows/copy-text-to-the-system-clipboard-on-click-with-javascript-1c0k

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To