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.

Objective

Implementing a copy to clipboard feature using native JavaScript.

Approach

We are going to use

execCommand

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

Code

Here is the code.

HTML


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


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

Here is the JavaScript code.

JavaScript

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

  /* Select the text field */
  copyText.select();

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* 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.