I'm trying to copy text from a textarea without having to click on a button. I'm using execCommand('copy')
and I can get it to copy the text but only when the button has been clicked and not programmatically.
Is there a way to do this?
var button = document.querySelector('button');
var area = document.querySelector('textarea');
button.addEventListener("click", function(){
area.select();
var msg = document.execCommand('copy') ? "successful" : "unsuccessful";
console.log("Copy " + msg);
});
button.click(); // Does not copy successfully
<textarea>Text to Copy</textarea>
<button>Copy</button>