URL: https://www.progressiverobot.com/js-clipboardjs/

clipboard.js lets you easily copy text to the clipboard. At 3kb gzipped and no need for Flash, it's a great lightweight way to allow your visitors to copy bits of text and code on your site.

Installation

clipboard illustration for: Installation

Install with npm:

				
					
npm install clipboard --save

				
			

Or get the package from Github and place the clipboard.min.js file manually in your project folder.

Then include the JavaScript file before the closing </body> tag:

				
					
&lt;script src="path/to/clipboard.min.js"&gt;&lt;/script&gt;

				
			

Finally, you'll want to instantiate it. In the following JQuery example we're instantiating the object for all elements with a class of clipboard:

				
					
$( document ).ready(function() {

 var clipboard = new Clipboard('.clipboard');

});

				
			

Usage

To use it, either use the data-clipboard-text data attribute:

				
					
&lt;button class="clipboard"

 data-clipboard-text="This will be copied"&gt;

 Copy this

&lt;/button&gt;

				
			

Or use the data-clipboard-target data attribute:

				
					
&lt;span id="copy"&gt;This text will be copied&lt;/span&gt;





				
			

Handling errors

Handle success and error states easily with the success and error custom events:

				
					
$( document ).ready(function() {

 clipboard.on('success', function(e) {

 $(e.trigger).text("Copied!");

 e.clearSelection();

 setTimeout(function() {

 $(e.trigger).text("Copy");

 }, 2500);

 });





				
			

Note: Some browsers don't support the execCommand API needed for clipboard.js to work properly. The text will still get selected, so a good workaround is to show a message telling the user to hit CTRL+C when an error event is triggered.