In this tutorial we will learn about clipboard.js which helps in copying text to clipboard.
Click here to visit clipboard.js GitHub repository.
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.
Include the clipboardjs script in the page.
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".
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");
In the following example we have an input field and a button. On clicking the button the content of the input field is copied.
<input id="foo" value="Hello World from the input field.">
<button class="clipboard" data-clipboard-target="#foo">Click to copy</button>
In the following example we have a textarea and on clicking the button its content is copied.
<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>
var clipboard = new Clipboard(".clipboardjs");
Have fun learning :-)
Copyright © 2014 - 2020 DYclassroom. All rights reserved.
rendered in 0.0142 sec