Skip to content

Instantly share code, notes, and snippets.

@theenoahmason
Created January 10, 2019 20:08
Show Gist options
  • Save theenoahmason/f1748155393349f6cd471e10670959fe to your computer and use it in GitHub Desktop.
Save theenoahmason/f1748155393349f6cd471e10670959fe to your computer and use it in GitHub Desktop.
Cross Browser Copy To Clipboard function
// Must be called directly in a "short interaction event handler"
// like `click` or `mousedown`/`touchstart`. Cannot be triggered from
// an <a> anchor element, even if `e.preventDefault()` is called on the
// event. passed `input` must be an <input> of any type or a <textarea>.
export function copyToClipboard(input = null) {
if (! input || (['INPUT', 'TEXTAREA'].indexOf(input.tagName) === -1)) {
throw new Error('A Valid <input> or <textarea> HTML element must be passed as the first parameter.');
}
// check if device is iOS.
const isIos = /iPhone|iphone|iPod|ipod|iPad|ipad/.test(window.navigator.userAgent);
if (isIos) {
// if is iOS, do all of this ridiculousness.
const oldContentEditable = input.getAttribute('contenteditable');
const oldReadOnly = input.getAttribute('readonly');
input.setAttribute('contenteditable', true);
input.setAttribute('readonly', false);
const range = document.createRange();
range.selectNodeContents(input);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
input.setSelectionRange(0, input.value.length);
input.setAttribute('contenteditable', oldContentEditable);
input.setAttribute('readonly', oldReadOnly);
} else {
// else just select the input :)
input.select();
}
// copy the selected text.
document.execCommand('copy');
// blur immediately so that the keyboard never shows.
input.blur();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment