javascript copy paste image clipboard code example
Example 1: 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 2: javascript copy to clipboard
const copyToClipboard = () => {
navigator.permissions.query({name: "clipboard-write"}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
updateClipboard('I copy this string');
}
});
};
const updateClipboard = (newClip) => {
navigator.clipboard.writeText(newClip).then(() => {
console.log('success');
}, () => {
console.log('Failed to copy');
});
};
const btn = document.getElementById('copy-button');
btn.addEventListener('click', copyHashtagToClipboard);