How to Copy to Clipboard in JavaScript

how to copy to clipboard using javascript

In this short tip post, we will learn how to copy text to clipboard using JavaScript.


Implementing a copy to clipboard feature using native JavaScript.


We are going to use


function to execute the copy command. This function is supported in majority of the browser including Chrome, Firefox and Safari. Check the compatibility here.


Here is the code.


<input type="text" value="Copy me!" id="myInput">

<button onclick="copyText()">Copy text</button>

Here is the JavaScript code.


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

  /* Select the text field */;

  /* Copy the text inside the text field */

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

Check out the codepen for the live demo.

See the Pen
copy clipboard
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.