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:
https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js
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.