Rose Rose - 6 months ago 129
HTML Question

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" />

Answer

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>

Comments