How to copy text to clipboard with JavaScript
HTML JavaScript

How to copy text to clipboard with JavaScript

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

Put your programming hat on! This tutorial shows how to copy text to clipboard using JavaScript.

For security, Most browsers make it difficult to copy text to the clipboard without an action triggered by the user.

The HTML markup

<input type="text" id="mytextbox" value="Click the button to copy this text to your clipboard">
<button onclick="copyText()" id="mybutton">Copy text</button>

Lets add some style

#mytextbox{
  width:200px;
  border: 1px solid grey;
  padding: 10px;
}
#mybutton{
  background-color:dodgerblue;
  border:none;
  color:white;
  padding:10px;
}

The Script

function copyText()
{
  var elem=document.getElementById('mytextbox');
  var txt=elem.select();
  document.execCommand("copy");
  document.getElementById("mybutton").innerHTML="Text copied";
}

Run the code

See the Pen Copy text to clipboard using JavaScript by Mishel Shaji (@mishelshaji) on CodePen.