- The clipboard.js is the new library for to work with clipboard operation like cut and copy operation.
- The clipboard.js is a lightweight library having 2KB file.
- In this Demo,”We will learn to install clipboard.js and use it for a simple example”.
- The clipboard.js can be installed using npm install clipboard --save command.The following screenshot shows the terminal with clipboard.js installation:-
- To demonstrate clipboard.js we have created the ClipBoardJSDemo directory.The following screenshot shows the updated directory structure of ClipBoardJSDemo project:-
- In this example we have 2 textarea elements textarea1 and textarea2 and a button button1.When we click the button it copies the content of textarea1 to clipboard.We have added a success event listener to clipboard object which copies the clipboard content to textarea2.
- clipboard.js module provides attributes data-clipboard-action and data-clipboard-target to specify operation and the target element from which the content is copied to clipboard.
- The index.html file contains the HTML code and javascript to work with clipboard.The content of index.html file are as follows:-
<!DOCTYPE html> <html lang="en"> <head> <title>Clipboard.js Demo</title> <script src="node_modules/clipboard/dist/clipboard.min.js"></script> <style> .container{margin: 30px;} button{margin-left: 160px;} </style> </head> <body> <h2>textarea1 > Copy > Clipboard > textarea2</h2> <div style="display: flex"> <div class="container"> <h4 for="textarea1">Text Area 1:</h4> <textarea id="textarea1"> </textarea> </div> <div class="container"> <h4 for="textarea1">Text Area 2:</h4> <textarea id="textarea2"> </textarea> </div> </div> <button id="button1" data-clipboard-action="copy" data-clipboard-target="#textarea1"> Move Content </button> </body> <script> var clipboard = new Clipboard('#button1'), texarea2 = document.getElementById('textarea2'); clipboard.on('success', function(event) { textarea2.value=event.text; }); </script> </html>
- The output of this demo looks like following screenshot:-
- Enter some text in textarea1 and press the button to copy the content to clipboard.When content is copied to clipboard the success event handler copies the content to textarea2.The following screenshot shows the final output of this demo:-
- The demo code can be downloaded from following link:-