copy-to-clipboard code example
Example 1: javascript text to clipboard
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
Example 2: javascript copy to clipboard
function copyToClipboard(text) {
var input = document.body.appendChild(document.createElement("input"));
input.value = text;
input.focus();
input.select();
document.execCommand('copy');
input.parentNode.removeChild(input);
}
Example 3: js copy text to clipboard
function copy() {
var copyText = document.querySelector("#input");
copyText.select();
document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);
Example 4: 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 5: 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 6: copy to clipboard
navigator.clipboard.writeText('Text To Copy');