copy a variable to clipboard javascript code example
Example 1: html pass a string to clipboard
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
Example 2: copy text to clipboard javascript
navigator.clipboard.writeText("Hello World");
Example 3: 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 4: 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 5: copy to clipboard javascript dom
navigator.clipboard.writeText('Text');
Example 6: js copy string to clipboard
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);