implement copy to clipboard button javascript code example
Example 1: js copy text to clipboard
function copy() {
var copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);
Example 2: js copy string to clipboard
const el = document.createElement('textarea');
el.value = str; //str is your string to copy
document.body.appendChild(el);
el.select();
document.execCommand('copy'); // Copy command
document.body.removeChild(el);
Example 3: copy text to clipboard javascript
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
<p id="text">Hello</p>
<button onclick="copyToClipboard('#text')"></button>