copy text to clipboard javascript html code example

Example 1: javascript copy to clipboard

function copyToClipboard(text) {
  var input = document.body.appendChild(document.createElement("input"));
  input.value = text;
  input.focus();
  input.select();
  document.execCommand('copy');
  input.parentNode.removeChild(input);
}

Example 2: javascript copy to clipboard

var copyTextarea = document.getElementById("someTextAreaToCopy");
copyTextarea.select(); //select the text area
document.execCommand("copy"); //copy to clipboard