Search code examples
zeroclipboard

Using data-clipboard-target


I've been trying to implement codes second item from the below address https://github.com/zeroclipboard/zeroclipboard/blob/master/docs/instructions.md#text-to-copy

The below example looks like very nice. However I spent 8 hours and I couldn't be successful. http://zeroclipboard.org/#demo

Actually I need to use ZeroClipboard for two different elements. I can accomplish if I use for just one elements. Otherwise every time second constructed element's copy operation works.

<body>

      <div class="form-group">
         <label for="client_id" class="control-label">Client ID:</label>
         <button id="copy_id" data-clipboard-target="client_id">Copy ID</button>
         <input id="client_id" class="form-control" >
     </div>        
      <div class="form-group">
         <label for="client_id" class="control-label">Client ID:</label>
         <button id="copy_secret" data-clipboard-target="client_secret">Copy Secret</button>
         <input id="client_secret" class="form-control" >
     </div>     

     <script type="text/javascript" src="/js/ZeroClipboard.js"></script>

     <script>
                // I think I should write some codes here but which codes?
     </script>

</body>

Solution

  • After hours I found a way. I think this is the one way if a user wants to use with two different HTML elements.

    Sample code

    <!DOCTYPE html>
    <html lang="tr">
    <body>
      <div>
        <button id="copy_id" type="button" class="clip_button" type="button">
            copy id value
        </button>                           
        <input id="client_id" type="text" readonly>
      </div>
    
      <div>
        <button id="copy_secret" type="button" class="clip_button">
          copy secret value
        </button>
        <input id="client_secret" type="text" readonly>
      </div>
    
      <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.2.0/ZeroClipboard.min.js"></script>
    
      <script>
        $(function() { // jquery main function
    
           // fill inputs using fictive data
           $("#client_id").val("ClientID112")
           $("#client_secret").val("ClientSecretWordSShh")
    
           // ***** copy to clipboard operations **********************
           var client = new ZeroClipboard( $('.clip_button'), {
               moviePath: "//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.2.0/ZeroClipboard.swf"
           } )
    
           client.on("copy", function(e) {
           var clipboard = e.clipboardData;
           if(e.target.id == "copy_id")
               clipboard.setData("text/plain", $("#client_id").val())
           else
               clipboard.setData("text/plain", $("#client_secret").val())
           })
           // ***** end of copy to clipboard operations ****************
    
        }) // end of jquery
      </script>
    </body>
    </html>