Add A Copy Button for the Code Block in the Jekyll Website

Jun. 11, 2025 • Updated Jun. 11, 2025

Today, I added a copy button for each code block in my Jekyll website, based on the reference1.

At first, add such button styles in the .\_sass\_buttons.scss file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Copy-button style for the code block
@mixin button-copycode-style {
  background-color: #575757;
  color: white;
  font-weight: bold;
  padding-left: 0.7em;
  padding-right: 0.7em;
  position: absolute;
  top: -7px;
  right: 10px;
  outline: none;

  @extend %deactive-user-selection;
}

.btn.btn--copycode {
  @include button-copycode-style;
  color: white;
}

.btn.btn--copycode-success {
  @include button-copycode-style;
  color: white;
}

Then, add the following JavaScript code in the .\_includes\footer_scripts.html file to add a copy button for each code block on the webpage and set the respond to user’s click:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- Add a copy button for the code block -->
<script type="text/javascript">
  function InitCopyPaste() {
      const codeBlocks = document.querySelectorAll("div.highlighter-rouge .rouge-code");

      codeBlocks.forEach((codeblock, index) => {
        const code = codeBlocks[index].innerText;
        const copyCodeButton = document.createElement("button");
        copyCodeButton.innerHTML = "Copy";
        copyCodeButton.classList = "btn btn--copycode";

        // insert a copy button
        copyCodeButton.onclick = function () {
          window.navigator.clipboard.writeText(code.trim());
          copyCodeButton.innerHTML = "Copied!";
          copyCodeButton.classList.add("btn--copycode-success");
          copyCodeButton.classList.remove("btn--copycode");

          setTimeout(() => {
            copyCodeButton.innerHTML = "Copy";
            copyCodeButton.classList.remove("btn--copycode-success");
            copyCodeButton.classList.add("btn--copycode");
          }, 2000);
        };

        // make the button
        codeblock.appendChild(copyCodeButton);
      });
    }
    document.addEventListener("DOMContentLoaded", InitCopyPaste);
</script>

Here is a result:

image-20250611152036420


References