Created
March 19, 2019 12:57
-
-
Save ajitsinghkamal/b02d5daf36f980fd15efa4b5a2e37136 to your computer and use it in GitHub Desktop.
Copy content to clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* copy content of an element or data from a list to clipboard | |
* | |
* @param valueList {Array} list of object or plain list | |
* | |
* @param key {String} used to identify the object key whose value | |
* should be copied in case the provided valueList parameter is a list of object | |
* | |
* @param selector {String} query selector string - if provided, copies the content | |
* of a DOM element if query is successful | |
**/ | |
copyToClipboard (selector = false, valueList, key) { | |
// copy strings from a provided data structure | |
// useful in case of copying data from api responses | |
// or data not available in DOM | |
// TODO: add support for plain object along with list | |
if (valueArray) { | |
const _el = document.createElement('textarea') // create a textarea to hold all strings | |
valueArray.forEach(v => { | |
_el.value = _el.value + '\r\n' + v[key] | |
}) | |
el.setAttribute('readonly', '') // makes the textarea readonly | |
el.style.position = 'absolute' // hide from user view | |
el.style.left = '-9999px' // to avoid noticable flashing of created textarea | |
document.body.appendChild(_el) | |
_el.select() | |
document.execCommand('copy') | |
document.body.removeChild(_el) // remove textarea after successfull copy to clipboard | |
} | |
// copy from an existing element in DOM | |
else if (selector) { | |
const range = document.createRange() | |
range.selectNode(document.querySelector(selector)) | |
window.getSelection().removeAllRanges() | |
window.getSelection().addRange(range) | |
document.execCommand('copy') | |
window.getSelection().removeAllRanges() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment