javascript copy text toclipboard 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: js copy to clipboard

Also works on safari!
  
function copyToClipboard() {
    var copyText = document.getElementById("share-link");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    document.execCommand("copy");
}

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);