Copy range text using Clipboard.js

I use clipboard.js and you need to copy the text in the gap by clicking a button. Is there any way to do this?

HTML:

<span id="spanId">text here</span> <input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId" /> 
+7
javascript html clipboard
source share
3 answers

The solution may be:

 // create a new instance of Clipboard plugin for the button element // using the class selector: .buttonClass var clipboard = new Clipboard('.buttonClass'); // when text is copied into clipboard use it clipboard.on('success', function(e) { $('#log').text('Text copied into clipboard is: <' + e.text + '>'); e.clearSelection(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script> <span id="spanId">text here</span> <input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId"/> <p id="log"></p> 
+3
source share

I'm still learning JS, but I found this on github clipboard.js here . I would make this comment, but did not have a reputation.

 <!-- Target --> <span id="spanId">text here</span> <!-- Trigger --> <button class="btn" data-clipboard-target="#spanId"> <img src="assets/clippy.svg" alt="Copy to clipboard"> </button> 

ive also never saw an input type button before she looked at the mozilla dev network here , and it says that "... it was replaced in HTML5 with an element." Therefore, I might think that this is the best way to do this.

+2
source share

You just need to instantiate a new clipboard. In this case, you will write new Clipboard(".buttonClass") , because this class has your button. The markup you provided was fully functional. I made a JSFiddle that you can view here .

If you are having other problems, I found clipboard.js docs to be very useful.

+2
source share

All Articles