After clicking on a table cell, I can copy the text but not after clicking on a button. Any suggestions on how to solve this issue? I suspect the problem might be in this line of JS:
const el = document.createElement('textarea');
, but I'm unsure.
https://codepen.io/S4UCY/pen/abNpyWB
/* Copy after clicking on text */
document.querySelectorAll(".table-cell").forEach(function(elm){
elm.addEventListener("click", function(e){
e.target.style.backgroundColor = 'green';
var copyText = e.target.textContent;
const el = document.createElement('textarea');
el.value = copyText;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
/* Alert the copied text */
alert("Copied the text: " + el.value);
});
})
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
td button{
float: right;
}
td button:before {
content: "Copy";
}
<table class="table">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<td class="table-cell" id="myInput" scope="row">kaching<button onclick="myFunction()" type="button" name="button"></button></td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td class="table-cell">Jacob </td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td class="table-cell">Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">