1 minute read

Ever wanted to copy something to the clipboard programmatically using javascript? Here’s how to do it for few different use cases.

Simple Use Cases

We can use following simple function to copy any variable to clipboard.

  function CopyToClipBoardHandler(value) {
    const copyListener = event => {
      document.removeEventListener('copy', copyListener, true);
      event.preventDefault();
      const clipboardData = event.clipboardData;
      clipboardData.clearData();
      clipboardData.setData('text/plain', value);
    };
    document.addEventListener('copy', copyListener, true);
    document.execCommand('copy');
  }
}

Demo

Advanced Use Cases

We can use clipboardjs to implement advanced requirements. You can set it up with few lines of code, it doesn’t have any external dependencies, and it’s only 3KB.

    <!-- 1. Define some markup -->
    <div id="btn" data-clipboard-text="1">
        <span>Copy</span>
    </div>

    <!-- 2. Include library -->
    <script src="clipboard.min.js"></script>

    <!-- 3. Instantiate clipboard by passing a HTML element -->
    <script>
    var btn = document.getElementById('btn');
    var clipboard = new Clipboard(btn);
    clipboard.on('success', function(e) {
        console.log(e);
    });
    clipboard.on('error', function(e) {
        console.log(e);
    });
    </script>

More examples can be found on github.

Demo

Important

  • Copy commands triggered from document.execCommand() will only work if the event is dispatched from an event that is trusted and triggered by the user.

  • Browser compatibility

    Chrome logo Edge logo Firefox logo Internet Explorer logo Opera logo Safari logo
    42+ 12+ 41+ 9+ 29+ 10+

Updated: