Last active
December 27, 2023 05:08
-
-
Save dgrebb/24b7a21e89c34a8620622257f9144c2f to your computer and use it in GitHub Desktop.
DOM element `innerHTML` copy on click or keyboard
This file contains 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
/** | |
* Copies text inside the clicked DOM node | |
* | |
* @param {Event} e The event which triggered the copy. | |
* @returns {Clipboard.writeText} Text is written to the system clipboard. | |
* | |
* @async | |
* | |
* ## Example: | |
* ```javascript | |
* const codes = document.querySelectorAll('code'); | |
* codes.forEach(function (code) { | |
* code.addEventListener('click', function (e) { | |
* copyText(e); | |
* }); | |
* }); | |
* ``` | |
*/ | |
export async function copyText(e) { | |
const text = e.target.innerHTML; | |
if (e.type === 'click' || e.code === 'Enter' || e.code === 'Space') { | |
try { | |
await navigator.clipboard.writeText(text); | |
// Handle success, e.g., show a notification | |
} catch (error) { | |
console.error('Error copying text to clipboard:', error); | |
// Handle the error, e.g., show an error message | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment