js make a copy 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: copy object javascript
var x = {key: 'value'}
var y = JSON.parse(JSON.stringify(x))
//this method actually creates a reference-free version of the object, unlike the other methods
//If you do not use Dates, functions, undefined, regExp or Infinity within your object
Example 3: 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);