

Copying text to clipboard with JavaScript
source link: https://www.tuicool.com/articles/RfI3uya
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


In this article, I will be explaining in depth how the copyToClipboard snippet from 30 seconds of code works. You can find the source code for it and a ton of other useful methods in the project’s repository.
30 seconds of code:Javascript snippets that you can understand in 30 seconds or lessCore functionality
One thing that comes up quite often inwebsite building is the ability to copy some text to clipboard, without the user selecting it or hitting the appropriate key combination on their keyboard.Javascript can easily do this in five short steps:
- Create a
<textarea>
element to be appended to the document. Set itsvalue
to the string that we want to copy to the clipboard. - Append said
<textarea>
element to the current HTML document. - Use
HTMLInputElement.select()
to select the contents of the<textarea>
element. - Use
Document.execCommand('copy')
to copy the contents of the<textarea>
to the clipboard. - Remove the
<textarea>
element from the document.
The simplest version of this method should look like this:
const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); };
(copyToClipboard method basic implementation)
clickevent listener), due to the way
Document.execCommand()works.
Making the appended element invisible
<textarea>element is appended and then removed. This problem is especially bad for people on screenreaders, as it can cause some really annoying issues. So, the next logical step is to use some CSS to make this element invisible and make it
readonlyin case the users try to mess with it:
const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); };
(copyToClipboard implementation without the textarea being shown)
Saving and restoring the original document’s selection
The final consideration is that the user might have already selected some content on the HTML document, so it would be nice to not remove anything they might have selected. Luckily, we can now use some modern Javascript methods and properties like
DocumentOrShadowRoot.getSelection(),
Selection.rangeCount,
Selection.getRangeAt(),
Selection.removeAllRanges()and
Selection.addRange()to save and restore the original document selection. Here’s the final, annotated code implementing these improvements:
const copyToClipboard = str => { const el = document.createElement('textarea'); // Create a <textarea> element el.value = str; // Set its value to the string that you want copied el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof el.style.position = 'absolute'; el.style.left = '-9999px'; // Move outside the screen to make it invisible document.body.appendChild(el); // Append the <textarea> element to the HTML document const selected = document.getSelection().rangeCount > 0 // Check if there is any content selected previously ? document.getSelection().getRangeAt(0) // Store selection if found : false; // Mark as false to know no selection existed before el.select(); // Select the <textarea> content document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events) document.body.removeChild(el); // Remove the <textarea> element if (selected) { // If a selection existed before copying document.getSelection().removeAllRanges(); // Unselect everything on the HTML document document.getSelection().addRange(selected); // Restore the original selection } };
(Final form of copyToClipboard with selection storing)
And that’s pretty much all there is to it. In less than 20 lines of code, we have created one of the most commonly needed methods in frontend development.
If you like this article, check out 30 seconds of code for more useful code snippets for your Javascript projects!
Recommend
-
61
In this article we will look at the various ways an object can be copied in Javascript. We will take a look at both shallow and deep copying. Before we begin, it is worth mentioning a few basics: objects in J...
-
68
README.md System Copy System copy provides vim mappings for copying / pasting text to the os specific clipboard. Most people will be happy just settin...
-
11
Copying Text to the Clipboard in MATLAB Web App – Fail » Stuart’s MATLAB Videos I want to occasionally copy text from data in a table in my web app, so I try to add a line to the cell selection callback to copy the cell value to the...
-
14
How to Get or Set Clipboard Text in Python2021-02-03Python103 words 1 min read 76 times readThere are several Python packages by which we can get and...
-
12
macOCR macOCR is a command line app that enables you to turn any text on your screen into text on your clipboard. When you envoke the ocr command, a "screen capture" like cursor is shown. Any text within the bounds will...
-
4
Of course the user can just select the text and copy it but giving them a button that they can click to copy it seems like a better idea(better UX). So in this article I will show you how you can copy text to clipboard using JavaScript....
-
5
LinkedIn says it will stop repeatedly copying iOS clipboard TikTok was caught doing the same thing ...
-
7
Samsung Keyboard gets improved clipboard and text correction Samsung has begun seeding a new update for its Samsung Keyboard and it...
-
6
How to Copy Text and Images to Clipboard in Javascript? Jun 9, 2022 , by Agnidipta Bhattacharjee and
-
4
For as long as anyone can remember, deep copying in JavaScript was not a built-in feature and we had to resort to libraries or workarounds to create a deep copy of a JavaScript value.That has changed now.- Advertisement -
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK