How to make a copy to clipboard button?

Home » Blog » How to make a copy to clipboard button?

Copy to clipboard button was created easily using clipboard.js.

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).

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>

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).

<script>
var clipboard = new ClipboardJS('.btn');
clipboard.on('success', function(e) {
console.log(e);
});
clipboard.on('error', function(e) {
console.log(e);
});
</script>

Now, set the text to be copied and create an ID.

<div id="copy-css">
#et-top-navigation .mydashboard {
display: none;
}
</div>

Finally, create the button. Add the class name you instantiated and also add the div ID on the data target.

<button class="btn" data-clipboard-target="#copy-css">
Click to copy
</button>

At this moment, the button should now work. To demonstrate, you can check the live result of this tutorial here.