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" />
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With