Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active July 25, 2017 15:49
Show Gist options
  • Save sekoyo/12dcc416026d33b601f6d7d09fbcdff1 to your computer and use it in GitHub Desktop.
Save sekoyo/12dcc416026d33b601f6d7d09fbcdff1 to your computer and use it in GitHub Desktop.
Copy to clipboard
export const copyToClipboard = (function initClipboardText() {
const id = 'copy-to-clipboard-helper';
const element = document.getElementById(id);
const textarea = element || document.createElement('textarea');
if (!element) {
textarea.id = id;
// Place in top-left corner of screen regardless of scroll position.
textarea.style.position = 'fixed';
textarea.style.top = 0;
textarea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textarea.style.width = '1px';
textarea.style.height = '1px';
// We don't need padding, reducing the size if it does flash render.
textarea.style.padding = 0;
// Clean up any borders.
textarea.style.border = 'none';
textarea.style.outline = 'none';
textarea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textarea.style.background = 'transparent';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
}
return function setClipboardText(text) {
textarea.value = text;
// iOS Safari blocks programmtic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
} else {
textarea.select();
}
try {
return document.execCommand('copy');
} catch (err) {
return false;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment