How to create action copy and paste in Javascript?

This snippet will help you create an action for copy and paste. Add function below into your Javascript file:

function copyStringToClipboard(str) {
  var el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly", "");
  el.style = { position: "absolute", left: "-9999px" };
  document.body.appendChild(el);
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
}
Copy this code


Usage:

const btn = document.getElementById("button");
const result = document.getElementById("result");

btn.addEventListener("click", function() {
  const stringX = "Please, copy me!!";
  copyStringToClipboard(stringX);
  result.innerHTML = "Copied! You can paste me to anywhere";
});

Copy this code


In your HTML file:

<button id="button">Copy</button>
<div id="result"></div>
Copy this code


Demo: