a blog for those who code

Wednesday 22 February 2017

Copy To Clipboard in JavaScript

In this post we will be discussing about how to do "Copy To Clipboard" functionality in JavaScript. This functionality is used extensively now a days by designers and developers to help users. A few years ago it was impossible for browsers to directly use the clipboard, but today basic clipboard integration is possible after an event is fired by the user.

Take GitHub Clone or download feature as an example which gives an option to copy the URL in the clipboard.


Using execCommand()


Copy to clipboard feature can be done in JavaScript using the method document.execCommand(). We have to add an input element or a textarea element with the text to be copied to the DOM. Then, we select the content and execute the copy command with document.execCommand('copy') which will copy the actual selected content.

This command is now supported by all the latest versions of browsers as shown below :

PC : http://caniuse.com/#search=execCommand

Working Example


<input class="textarea1" value="Copy this text"></input>
<button class="copybtn btn">Copy Textarea></button>

<script>
 document.querySelector('.copybtn').onclick = function () {
  document.querySelector('.textarea1').select();
  document.execCommand('copy');
 }
</script>


Using Clipboard.js


The clipboard.js API for copy to clipboard is short and sweet. Simple example is

<input id="foo" type="text" value="Copy this text">
<button class="copy-button" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>

var clipboard = new Clipboard('.copy-button');

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment