Implementing Copy-to-Clipboard Features in JavaScript

  • June 11, 2023
  • 3 min read

Welcome back to another DevPicker blog post! Today, we're diving into an important aspect of user interaction – how to implement a copy to clipboard feature using JavaScript. This simple yet powerful feature can drastically enhance your user's experience, allowing them to conveniently copy text with a single click. In this post, we'll explore two methods: the modern navigator.clipboard method and the older execCommand("copy") method. So, let's dive right in!

The Modern Way: Using navigator.clipboard

The navigator.clipboard API offers a more modern, standardized way of interacting with the clipboard, ideal for newer projects. Here's how you can utilize it to copy text to the clipboard:

    
      function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
          console.log('Text copied to clipboard');
        }).catch(function(err) {
          console.error('Failed to copy text: ', err);
        });
      }
    
  

To use this function, you just need to pass the text you want to copy to the clipboard. Here's an example:

    
      copyToClipboard('Hello, DevPicker!');
    
  

Copying Text from an Input

How about copying text directly from an HTML input field? Here's how you can do it:

    
      function copyFromInput(inputElement) {
        let textToCopy = inputElement.value;
        navigator.clipboard.writeText(textToCopy).then(function() {
          console.log('Text copied to clipboard');
        }).catch(function(err) {
          console.error('Failed to copy text: ', err);
        });
      }
    
  

The Older Way: Using execCommand("copy")

If you're working with an older browser that doesn't support the navigator.clipboard API, the execCommand("copy") is a viable alternative. Here's how to use it:

    
      function copyToClipboard(text) {
        var dummy = document.createElement("textarea");
        document.body.appendChild(dummy);
        dummy.value = text;
        dummy.select();
        document.execCommand("copy");
        document.body.removeChild(dummy);
        console.log('Text copied to clipboard');
      }
    
  

To copy from an input, simply replace text with the value of the input element:

    
      function copyFromInput(inputElement) {
        var textToCopy = inputElement.value;
        var dummy = document.createElement("textarea");
        document.body.appendChild(dummy);
        dummy.value = textToCopy;
        dummy.select();
        document.execCommand("copy");
        document.body.removeChild(dummy);
        console.log('Text copied to clipboard');
      }
    
  

Combining New and Old Methods with a Fallback

In some situations, you might need to use the newer navigator.clipboard method and have execCommand("copy") as a fallback. Here's how to achieve that:

    
      function copyToClipboard(text) {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(text).then(function() {
            console.log('Text copied to clipboard');
          }).catch(function(err) {
            console.error('Failed to copy text: ', err);
          });
        } else {
          var dummy = document.createElement("textarea");
          document.body.appendChild(dummy);
          dummy.value = text;
          dummy.select();
          document.execCommand("copy");
          document.body.removeChild(dummy);
          console.log('Text copied to clipboard');
        }
      }
    
  

Improving copyFromInput Function

Let's also modify our copyFromInput function. If it's a string, we will use it as a selector to get the element. Otherwise, we'll try to get its value directly. We will also add checks to ensure that the querySelector or the passed element is valid:

    
      function copyFromInput(input) {
        let inputElement = typeof input === 'string' ? document.querySelector(input) : input;
        if (!inputElement || !('value' in inputElement)) {
          console.error('Invalid input');
          return;
        }
        
        const textToCopy = inputElement.value;

    if (navigator.clipboard) {
      navigator.clipboard.writeText(textToCopy).then(function() {
        console.log('Text copied to clipboard');
      }).catch(function(err) {
        console.error('Failed to copy text: ', err);
      });
    } else {
      var dummy = document.createElement("textarea");
      document.body.appendChild(dummy);
      dummy.value = textToCopy;
      dummy.select();
      document.execCommand("copy");
      document.body.removeChild(dummy);
      console.log('Text copied to clipboard');
    }
  }

With these changes, the copyFromInput function can now handle a wider range of use cases. We've also introduced a more graceful error handling strategy for invalid inputs.


Don't forget to test your copy to clipboard functionality across different browsers and scenarios to ensure the best user experience. Happy coding!

As a practical example of the copy-to-clipboard function in action, check out our Slugify tool. This handy tool generates URL-friendly slugs from your input string and provides a copy-to-clipboard option for the result! Happy coding!


JavaScriptWeb DevelopmentUser ExperienceClipboardFrontendCoding Tutorial

JavaScriptWeb DevelopmentUser ExperienceClipboardFrontendCoding Tutorial