Skip to content

Instantly share code, notes, and snippets.

@tjbenton
Created May 24, 2016 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tjbenton/26b574e1c32492e9171012dd5795a50f to your computer and use it in GitHub Desktop.
Save tjbenton/26b574e1c32492e9171012dd5795a50f to your computer and use it in GitHub Desktop.
select text inside of an element and then copy it to the clipboard
function copy(obj) {
try {
if (obj) selectContent(obj)
document.execCommand('copy')
// clears the current selection
window.getSelection().removeAllRanges()
} catch (err) {
console.log(err)
}
}
function selectContent(obj) {
if (window.getSelection && document.createRange) {
let sel = window.getSelection()
let range = document.createRange()
range.selectNodeContents(obj)
sel.removeAllRanges()
sel.addRange(range)
} else if (document.selection && document.body.createTextRange) {
let textRange = document.body.createTextRange()
textRange.moveToElementText(obj)
textRange.select()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment