Menu

gitpiper

copyToClipboard javascript Code Snippet in 2024

browserstringeventadvanced

Last Updated: 16 December 2024

Copies a string to the clipboard. Only works as a result of user action (i.e. inside a click event listener).

  • Create a new <textarea> element, fill it with the supplied data and add it to the HTML document.
  • Use Selection.getRangeAt()to store the selected range (if any).
  • Use Document.execCommand('copy') to copy to the clipboard.
  • Remove the <textarea> element from the HTML document.
  • Finally, use Selection().addRange() to recover the original selected range (if any).
  • Note: You can use the asynchronous Clipboard API in most current browsers. You can find out more about it in the copyToClipboardAsync snippet.
const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand('copy'); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } };
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.

javascript snippet similar to copyToClipboard For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️