Creating Copy to clipboard button using ClipboardJS.

How to Create Copy to Clipboard Button Using ClipboardJS?

In this tutorial, I will show you an easy example of how to create a copy to clipboard button using the ClipboardJS library. Follow these steps:


Add clipboard.min.js JavaScript Between Head Tag

Add the following JavaScript using the CDNJS URL into the script tags:


Create a Textarea Item

Create a textarea item and specify the ID myText. Below is an example:

<textarea id="myText"></textarea>

Create a Copy Button

Create a button and specify an ID or Class. This is important because that ID or Class will be used by the ClipboardJS. Also, you need to specify the attribute for the action type data-clipboard-action="copy" and one more attribute for the target element ID data-clipboard-target="#myText". This will target the above textarea. Below is an example:

<button type="button" class="copy" data-clipboard-action="copy" data-clipboard-target="#myText">Copy to Clipboard</button>

Add JavaScript Code

Now add the following JavaScript code in the head tags between script tags:

  new ClipboardJS('.copy');

You can notice that we specify the button class here as .copy. If you specified an ID or another class then you need to pass that ID or class name. For example:

 new ClipboardJS('#idCopy');

It is done. We have created a copy to clipboard button using the ClipboardJS JavaScript library. Now when you will click the Copy to Clipboard button, it will select and copy the text of the textarea item.

Written by Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of and a question and answer forum for developers. You can connect with me on Facebook and Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *