Skip to content

Instantly share code, notes, and snippets.

@dgrebb
Last active December 27, 2023 05:08
Show Gist options
  • Save dgrebb/24b7a21e89c34a8620622257f9144c2f to your computer and use it in GitHub Desktop.
Save dgrebb/24b7a21e89c34a8620622257f9144c2f to your computer and use it in GitHub Desktop.
DOM element `innerHTML` copy on click or keyboard
/**
* 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