I have scoured this site's similar questions, but I'm still at a loss.
Basically, I'm taking over a project for a co-worker who is moving on. His plans for an intranet page is supposed to have multiple textareas each with its own predefined text and their own "copy text" button.
On click, it copies to the user's clipboard. I pulled apart the code and for whatever reason, when I add new textareas and a button, it will not copy. The first one will.
What am I missing or doing wrong?
<html>
<head>
<script>
window.onload = function () {
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function (event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Whoops, unable to copy');
}
});
}
</script>
</head>
<body>
<p>Test #1 </p>
<div>
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hello. This is textarea test bed #1</textarea>
<button class="js-textareacopybtn">Copy Text (works)</button>
<p>Test #2:</p>
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hi! Welcome to textarea test bed #2 </textarea>
<button class="js-textareacopybtn">Copy Text (broken)</button>
</div>
</body>
</html>