How to make a copy to clipboard button?
So here’s how I create the copy to clipboard button…
Firstly, I added the clipboardjs script hosted from cdnjs.com on top of my post (can either be on the head or body tag).
[sourcecode language=”plain”]<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
[/sourcecode]
Next, is I added another js script to instantiate the clipboard by passing a string selector. (you can also do it by passing an HTML element or lists of HTML elements).
[sourcecode language=”plain”]<script>
var clipboard = new ClipboardJS(‘.btn’);
clipboard.on(‘success’, function(e) {
console.log(e);
});
clipboard.on(‘error’, function(e) {
console.log(e);
});
</script>[/sourcecode]
Now, set the text to be copied and create an ID.
[sourcecode language=”plain”]<div id="copy-css">
#et-top-navigation .mydashboard {
display: none;
}
</div>[/sourcecode]
Finally, create the button. Add the class name you instantiated and also add the div ID on the data target.
[sourcecode language=”plain”]<button class="btn" data-clipboard-target="#copy-css">
Click to copy
</button>[/sourcecode]
At this moment, the button should now work. To demonstrate, you can check the live result of this tutorial here.