Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy span text using Clipboard.js

I'm using clipboard.js and need to copy the text in a span by clicking a button. Is there a way to do this?

HTML:

<span id="spanId">text here</span>
<input type="button" class="buttonClass" value="Copy" data-clipboard-target="#spanId" />
like image 860
Rose Avatar asked May 19 '16 17:05

Rose


People also ask

How can I copy text to clipboard with JavaScript?

To copy text with the new Clipboard API, you will use the asynchronous writeText() method. This method accepts only one parameter - the text to copy to your clipboard. This can be a string, a template literal holding variables and other strings, or a variable used to hold a string.


2 Answers

A solution can 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>
like image 145
gaetanoM Avatar answered Oct 03 '22 16:10

gaetanoM


You'll just need to instantiate a new Clipboard. In this case you'd write new Clipboard(".buttonClass") because that's the class your button has. The markup you've provided was completely functional otherwise. I've made a JSFiddle that you can view here.

If you're having any other trouble, I found the clipboard.js docs to be very helpful.

like image 23
pinjasaur Avatar answered Oct 03 '22 18:10

pinjasaur