Well, in this article I gonna show you how to easily implement the ability to copy data to the clipboard. In order to implement it I will clipboard.js javascript library, let get started with me:
Installation
The first thing I need to do is include the clipboard.js library file in head tag of the application:
1
|
|
If you don’t wish to use a CDN, you can download the clipboard in other ways:
- Using npm, by running npm install clipboard --save
- Using bower, by running bower install clipboard --save
- By downloading a zip file from the clipboard.js github page and referencing it in your HTML.
Usage
Copy text from another element: A pretty common use case is to copy content from another element. You can do that by adding a data-clipboard-target
attribute in your trigger element. The value you include on this attribute needs to match another’s element selector.
1 2 3 4 5 6 7 |
|
Cut text from another element: Additionally, you can define a data-clipboard-action
attribute to specify if you want to either copy
or cut
content. If you omit this attribute, copy
will be used by default.
1 2 3 4 5 6 7 |
|
As you may expect, the cut action only works on input or textarea elements.
Copy text from attribute: Truth is, you don’t even need another element to copy its content from. You can just include a data-clipboard-text
attribute in your trigger element.
1 2 3 4 |
|
Events
There are cases where you’d like to show some user feedback or capture what has been selected after a copy/cut operation.
That’s why we fire custom events such as success and error for you to listen and implement your custom logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
So far so good, That’s it!!! See ya!!! :)