Copy highlighted code snippets to the clipboard in JavaScript

Allowing users to copy Code Snippets to clipboard is a popular convenience feature for Websites. In this article, I will show you how to add Copy to Clipboard functionality to your Web Apps

Ahmed Abdulrahman
Ahmed Abdulrahman
Jan 3rd, 2020 • ☕️ 1 min read
javascriptreact
Copy highlighted code snippets to the clipboard in JavaScript

Photo by David Klein on Unsplash

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 element
3 using `getSelection` function
4 */
5function textSelection(node) {
6 const selection = window.getSelection();
7 // We need to save the current selection, so we can
8 // later restore the selection
9 const selected = selection.rangeCount === 0 ? null : selection.getRangeAt(0);
10
11 const range = document.createRange();
12 range.selectNodeContents(node);
13 selection.removeAllRanges();
14 selection.addRange(range);
15
16 return { selection, selected}
17}
18
19/*
20 Programmatically Copy text content to the clipboard
21 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 text
28 btn.innerHTML = 'Copied';
29
30 // we set back button text
31 setTimeout(() => {
32 btn.innerHTML = 'Copy';
33 }, 2000);
34
35 } catch (err) {
36 // Error handling goes here and set back button text
37 btn.innerHTML = 'Copy';
38 } finally {
39 // Finally we need to backup the current selected text before
40 // copying and restore the previous selection
41 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 here
3 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!


Discuss on TwitterFollow @_ahmed_ab

Other things I've written