An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To