8

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" />
Rose
  • 363
  • 1
  • 3
  • 13

2 Answers2

3

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
2

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.

pinjasaur
  • 418
  • 3
  • 6