Copy text to clipboard in JavaScript using clipboard.js

Reference JavaScript

In this tutorial we will learn about clipboard.js which helps in copying text to clipboard.

Click here to visit clipboard.js GitHub repository.

Install

If you have Node and NPM installed then use the following command to install clipboardjs in your project as a dependency.

npm install clipboard --save

Or, download the latest release from there GitHub repository.

Or, get it from CDN.

Step 1: Include the script

Include the clipboardjs script in the page.

<script src="path/to/clipboard.min.js"></script>

Step 2: Create Markup

Create an input element and set some value.

<input id="foo" value="Hello World">

Now, create a button that will trigger the copy event.

<button class="clipboard" data-clipboard-target="#foo">Copy</button>

Note! We have added the clipboard class to the button which will be used to instantiate the Clipboard. And we have also added an attribute data-clipboard-target to the button. Its value is set to #foo which means it is targeting the element having id="foo".

Step 3: Instantiate

Next we instantiate the Clipboard object and we are passing the .clipboard class that we used in the button above.

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

Example

<!-- include clipboardjs and logic --><!-- include clipboardjs and logic ends here -->

In the following example we have an input field and a button. On clicking the button the content of the input field is copied.

HTML

<input id="foo" value="Hello World from the input field.">

<button class="clipboard" data-clipboard-target="#foo">Click to copy</button>

JavaScript

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

In the following example we have a textarea and on clicking the button its content is copied.

HTML

<textarea type='text' id='my-textarea' rows='6'>Hello World from the textarea.</textarea>

<button class='clipboardjs' data-clipboard-target='#my-textarea'>Click to copy</button>

JavaScript

var clipboard = new Clipboard(".clipboardjs");