Search code examples
javascripthtmlzeroclipboard

Add copy button in Javascript


I'm trying to add a button that will copy the text from a textarea using ZeroClipboard, however, when I click the button, nothing happens and when I paste nothing has been added to clipboard.

var clip = new ZeroClipboard( document.getElementById("btn4"), {
  moviePath: "https://rawgit.com/zeroclipboard/zeroclipboard/master/dist/ZeroClipboard.swf"
} );

clip.on( "load", function(client) {
  // alert( "movie is loaded" );

  client.on( "complete", function(client, args) {
    // `this` is the element that was clicked
    this.style.display = "none";
  } );
} );
<div id ="right" style = "float:left; width: 10%; margin-left:185px; margin-top:35px">
  <button id="btn4" data-clipboard-target="block2" name ="btn4" type="button" class="btn btn-success"><i class="icon-white icon-file"></i> Copy</button>

  <script src="https://rawgit.com/zeroclipboard/zeroclipboard/master/dist/ZeroClipboard.js"></script>
</div>

<textarea id="block2" name="block2" style="font-family:rockwell; background-color:#D1D1D1"></textarea>

Solution

  • Try:

    <script language="JavaScript">
            var copyTextareaBtn = document.querySelector('.btn4');
    
    copyTextareaBtn.addEventListener('click', function(event) {
      var copyTextarea = document.querySelector('.block2');
      copyTextarea.select();
    
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }
    });
    </script>