• Copying text to clipboard with JavaScript
  • Originally written by Angelos Chalaris

This article takes a closer look at how copyToClipboard blocks work in 30-second code. You can find the source code and many more useful methods in the project repository.

The core function

A common requirement when building a website is to copy text to the clipboard without the user selecting or using a keyboard combination. JavaScript can easily solve this problem in just five steps:

1. Create a

2. Insert the appeal

3. Use HTMLInputElement. Select () to select the contents of the

4. Use document. execCommand(‘copy’) to copy the contents of the

5. Remove the

The simplest version of this method looks something 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);
};
Copy the code

Remember, this method should not be used in every situation. Because of the way document.execcommand () works, it must be the result of a response to a user action.

Make the inserted element invisible

If you try the above method, you may see a flicker when the

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);
};
Copy the code

Save and restore the original document selection

The last thing to consider is that the user might already have selected some content in the HTML document, and it would be wise not to remove the content they selected. Luckily, We can use such as DocumentOrShadowRoot. GetSelection (), Selection. RangeCount, Selection. GetRangeAt (), Selection. RemoveAllRanges (), and Selection. The addRange ready-made JavaScript methods and properties such as () to save and restore the original document is selected. Here is the final modified code with comments:

const copyToClipboard = str= > {
  const el = document.createElement('textarea');  // Create a 
  el.value = str;                                 // Set its value to the string you want to copy
  el.setAttribute('readonly'.' ');                // Set it to read-only to prevent interference
  el.style.position = 'absolute';                 
  el.style.left = '-9999px';                      // Move it out of the screen to make it invisible
  document.body.appendChild(el);                  // Insert the 
  const selected =            
    document.getSelection().rangeCount > 0        // Check to see if the content has been selected before
      ? document.getSelection().getRangeAt(0)     // If found, save selected
      : false;                                    // Flag it false to indicate that the previously selected content does not exist
  el.select();                                    // Select the contents of 
  document.execCommand('copy');                   // Copy - works only if it is the result of a response to a user action (e.g., click event)
  document.body.removeChild(el);                  // Remove the 
  if (selected) {                                 // If the selected content already exists before copying
    document.getSelection().removeAllRanges();    // Uncheck all selected parts of the HTML document
    document.getSelection().addRange(selected);   // Restore the original selection}};Copy the code

That’s all. With less than 20 lines of code, we’ve created one of the most commonly used methods in front-end development.

If you like this article, give a clap (or fifty). Remember to check out the 30 second code to find more useful code blocks for your JavaScript projects!