js copy 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: copy to clipboard javascript
// Since Async Clipboard API is not supported for all browser!
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: javascript copy to clipboard
const copyToClipboard = () => {
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
// write to the clipboard now
updateClipboard('I copy this string');
}
});
};
const updateClipboard = (newClip) => {
navigator.clipboard.writeText(newClip).then(() => {
// clipboard successfully set
console.log('success');
}, () => {
// clipboard write failed
console.log('Failed to copy');
});
};
const btn = document.getElementById('copy-button');
btn.addEventListener('click', copyHashtagToClipboard);