programmatically copy to clipboard javascript code example

Example 1: javascript copy to clipboard

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

Example 2: copy text to clipboard javascript

<script>
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
</script>

<p id="text">Hello</p>
<button onclick="copyToClipboard('#text')"></button>