<div class="option">
<div id="result">TextContent</div>
<button id="copy">Copy</button>
</div>
let result = document.getElementById("result");
let copy = document.getElementById("copy");
copy.addEventListener("click", function () {
copyToClipboard(result.innerText);
});
function copyToClipboard(text, onComplete) {
if (navigator.clipboard) {
navigator.clipboard
.writeText(text)
.then(() => {
if (typeof onComplete === "function") onComplete();
})
.catch((err) => {
console.error("Copy fail", err);
});
} else {
let area = document.createElement("textarea");
document.body.appendChild(area);
area.value = text;
area.select();
document.execCommand("copy");
document.body.removeChild(area);
if (typeof onComplete === "function") onComplete();
}
}
В песочнице работать не будет