To demonstrate the implementation, we create required elements:
1<!-- User interaction is required by the browser -->2<button class="btn">Copy Code</button>3<pre style="position: relative">4 <code>5 <!-- Code Snippets goes here --->6 </code>7</pre>
Next, we query our elements:
1const btn = document.querySelector('.btn');2const codeBlock = document.querySelector('pre');
Then, we need a to have a helper functions to select and copy the text content of an element:
1/*2 Programmatically select the text content of code element3 using `getSelection` function4 */5function textSelection(node) {6 const selection = window.getSelection();7 // We need to save the current selection, so we can8 // later restore the selection9 const selected = selection.rangeCount === 0 ? null : selection.getRangeAt(0);1011 const range = document.createRange();12 range.selectNodeContents(node);13 selection.removeAllRanges();14 selection.addRange(range);1516 return { selection, selected}17}1819/*20 Programmatically Copy text content to the clipboard21 using the `document.execCommand('copy')`22*/23function copytoClipboard(selection, selected) {24 try {25 // In order Copy only, user action is required (e.g. click events)26 document.execCommand('copy');27 // once text is copied we update button text28 btn.innerHTML = 'Copied';2930 // we set back button text31 setTimeout(() => {32 btn.innerHTML = 'Copy';33 }, 2000);3435 } catch (err) {36 // Error handling goes here and set back button text37 btn.innerHTML = 'Copy';38 } finally {39 // Finally we need to backup the current selected text before40 // copying and restore the previous selection41 selection.removeAllRanges();42 selected && selection.addRange(selected);43 }44}
Finllay, handle user action by attaching onClick
event to button element:
1btn.addEventListener('click', () => {2 // we pass our codeblock here3 const {selection, currentRange} = textSelection(codeBlock)4 copytoClipboard(selection, currentRange)5})
And that’s pretty much all there is to it. Now you can easily adds this util to your Web Apps.
Did you find this useful? Buy me a coffee to give my brain a hug ☕️.
Hope you liked this article. If you did, then share it. It means a lot.🙌 Thanks for reading!