How to Copy to Clipboard in 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

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

<!-- The button used to copy the text -->
<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.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 299