Skip to content

Instantly share code, notes, and snippets.

@myfreeer
Last active August 26, 2018 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myfreeer/73931ae2210030fe2b25447fd21017dd to your computer and use it in GitHub Desktop.
Save myfreeer/73931ae2210030fe2b25447fd21017dd to your computer and use it in GitHub Desktop.
Copy text to clipboard
'use strict';
/**
* Copy text to clipboard
* @param {string | Element} text
* @return {boolean}
*/
const copy = (text = '') => {
if (text instanceof Function)
text = text();
let elem = text;
if (!(text instanceof Element)) {
// elem = document.createTextNode(text);
elem = document.createElement('textarea');
elem.setAttribute('readonly', true);
elem.style.cssText = 'position: absolute; left: -99999em';
elem.value = text;
document.documentElement.appendChild(elem);
}
const range = document.createRange();
range.selectNode(elem);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
if (elem instanceof HTMLInputElement) {
elem.select();
}
try {
const stat = document.execCommand('copy');
sel.removeAllRanges();
return stat;
} catch (e) {
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment