copy to clipboard in javascript

How to Copy to Clipboard in JavaScript

Often websites and web applications need to provide the ability for users to copy data to clipboard. Typically, this feature was not supported natively by browsers so it was not possible to copy to clipboard using JavaScript. Developers used to take help of flash based plugins for this purpose. Since flash is not supported any more by major browsers, developers rely on JavaScript to build this feature. Starting with HTML5, browsers have started supporting copy to clipboard features. In this article, we will learn how to build copy to clipboard in JavaScript.


How to Copy to Clipboard in JavaScript

Here are the steps to copy to clipboard in JavaScript.

1. Create HTML

First we create HTML code as shown below. Add it to an html file, say, test.html.

<html>

<body>
<!-- The text field -->
<input type="text" value="Hello World" id="myInput">

<!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>

</body>
</html>

In the above code we create a text box and button. When the button is clicked we want the text in text box to be copied to clipboard. We set onlick attribute of button to myFunction() so that it acts as the click handler.


2. Add Javascript

Add the following JavaScript code to your HTML file, in the <body> section. Here we will define the click handler myFunction() that we mentioned in onlick attribute of our button.

<script type="text/javascript">

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /* For mobile devices */

   /* Copy the text inside the text field */
  navigator.clipboard.writeText(copyText.value);

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}

</script>

In the above code, we first get hold of the text box and select it. Then we use navigator.clipboard.writeText() function to copy the data to clipboard. navigator.clipboard API can be used to cut, copy, paste data within web application. Finally we display the copied data in alert box.

Now if you open test.html in a web browser, enter text in textbox and click the button labelled ‘Copy Text’ it will display the text you entered in text box, in an alert box.

You can use it in your website or web application as per your requirement. HTML5 provides many useful capabilities to work with data and copy them to clipboard. This is supported by all major browsers.

Also read:

How to Get Query String Values in JavaScript
How to Check if Object is Empty in JavaScript
How to Return Response from Asynchronous Call in JavaScript
How to Remove Key from JavaScript Object
How to Deep Clone Objects in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *