Skip to content

Instantly share code, notes, and snippets.

@ting-dev-coder
Forked from tjbenton/copy.js
Created January 28, 2021 08:26
Show Gist options
  • Save ting-dev-coder/c2a7fec0c8b512335f6ca93d3657c592 to your computer and use it in GitHub Desktop.
Save ting-dev-coder/c2a7fec0c8b512335f6ca93d3657c592 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