onclick copy to clipboard code example
Example 1: onclick add to clipboard
<button onClick="SelfCopy(this.id)" id="1">1</button>
<button onClick="SelfCopy(this.id)" id="2">2</button>
<button onClick="SelfCopy(this.id)" id="3">3</button>
function SelfCopy(copyText)
{
navigator.clipboard.writeText(copyText);
alert("You just copied this: (" + copyText + ").");
}
Example 2: how to copy text in the clipboard in js
<html>
<input type="text" value="Hello world"(Can be of your choice) id="myInput"(id is the name of the text, you can change it later)
<button onclick="Hello()">Copy Text</button>
<script>
function Hello() {
var copyText = document.getElementById('myInput')
copyText.select();
document.execCommand('copy')
console.log('Copied Text')
}
</script>
Example 3: copy to clipboard javascript
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
Example 4: javascript copy to clipboard
var copyTextarea = document.getElementById("someTextAreaToCopy");
copyTextarea.select();
document.execCommand("copy");