The code below produces the code snippet shown above using HighlightJS [↗] and some custom JS to append a click to copy button to the snippet.
Code walkthrough
01: <pre>
02: <code>
03: function name() {
04: console.log("output")
05: }
06: </code>
07: </pre>
08:
09: <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
10:
11: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlightjs-themes@1.0.0/androidstudio.css" />
12:
13: <script>
14: hljs.highlightAll(); // initialize highlighting
15: </script>
16:
17: <!-- Code to append a click to copy button -->
18: <script>
19: var snippets = document.getElementsByTagName('pre');
20: var numberOfSnippets = snippets.length;
21: for (var i = 0; i < numberOfSnippets; i++) {
22: code = snippets[i].getElementsByTagName('code')[0].innerText;
23:
24: snippets[i].classList.add('hljs'); // append copy button to pre tag
25:
26: snippets[i].innerHTML = '<button class="hljs-copy">Copy</button>' + snippets[i].innerHTML; // append copy button
27:
28: snippets[i].getElementsByClassName('hljs-copy')[0].addEventListener("click", function () {
29: this.innerText = 'Copying..';
30: if (!navigator.userAgent.toLowerCase().includes('safari')) {
31: navigator.clipboard.writeText(code);
32: } else {
33: prompt("Clipboard (Select: ⌘+a > Copy:⌘+c)", code);
34: }
35: this.innerText = 'Copied!';
36: button = this;
37: setTimeout(function () {
38: button.innerText = 'Copy';
39: }, 1000)
40: });
41: }
42: </script>
43: <style>
44: .hljs-copy {
45: float: right;
46: cursor: pointer;
47: }
48: </style>
On line 14
HighlightJS is initialized and all snippets within a < code >
tag are highlighted.
The code from line 18
downward is responsible for adding the copy functionality.
For this to work make sure to have your < code >
tag within a < pre >
tag. This is because if we append our copy button into the code tag directly HighlightJS will override it and our button will be displayed as code so we need to place it within a parent tag.
Once we get the pre
tag element on line 25
we run a for loop to perform the following per each code snippet found on the page:
- Line(30) Append the
hljs
class to thepre
tag, this will apply the same CSS styling as the code section to thepre
tag section. For example, the background of where the copy button is found will have the same background as the code snippet to make it look uniform. - Line(32) Append a button with a class
hljs-copy
to thepre
tag, the class pulls in the CSS styling (line 46) that positions the button to the right and shows the pointer cursor when hovered upon. - Line(34-42) An event handler is added to listen for a click event which then copies the code snippet to the clipboard.
Here is another article you might like 😊 Automate deployment to AWS S3 using Github actions