Copy HTML Content to Clipboard using JavaScript

If you are working in a web development inputs or textarea or div, you might need to create a button like “Copy to Clipboard” to copy all contents of input or div to user’s clipboard for making it better for UI. So in this article, I have provided examples for how we can create cop-to-clipboard functionality using Javascript or jQuery in HTML.

Copy to Clipboard using Javascript

Let’s first create example to copy data from input element. In this we will be using document.execCommand(‘copy’) Browser API which copies contents of HTML input to clipboard

Steps to follow

  • Create a <textarea> and set its contents to the text you want to be copied to the clipboard.
var sampleTextarea = document.createElement("textarea");
  • Append the textarea to the DOM.
document.body.appendChild(sampleTextarea);
  • Select the text in the textarea using
sampleTextarea.select();
  • Call document.execCommand(“copy”) to copy contents from textarea into clipboard
document.execCommand("copy");
  • Remove the textarea from the document.
document.body.removeChild(sampleTextarea);

Complete function


function copyToClipboard(text) {
    var sampleTextarea = document.createElement("textarea");
    document.body.appendChild(sampleTextarea);
    sampleTextarea.value = text; //save main text in it
    sampleTextarea.select(); //select textarea contenrs
    document.execCommand("copy");
    document.body.removeChild(sampleTextarea);
}
function myFunction(){
    var copyText = document.getElementById("myInput");
    copyToClipboard(copyText.value);
}