Copy to Clipboard Using Javascript

less than 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);
      const clipboardData = event.clipboardData;
      clipboardData.setData('text/plain', value);
    document.addEventListener('copy', copyListener, true);


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">

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

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

More examples can be found on github.



  • 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+