ES6 snippet - JavaScript - Copy to clipboard - Copy string

PHOTO EMBED

Wed Nov 04 2020 09:00:08 GMT+0000 (Coordinated Universal Time)

Saved by @julien #javascript

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

// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
content_copyCOPY

https://medium.com/swlh/24-modern-es6-code-snippets-to-solve-practical-js-problems-3609f301859e