Web

The CopyCode Button applied to this site

Memo
BW Server
Install Maintenance HTTPS Connector
ISM
Install
BWMAgent
Linux Compile

Code 영역에 적용된 Copy Button 구현

1. jekyll-theme-cayman CodeBlock Structure

<pre>            
    <code class="language-JAVA">Code</code>
</pre>

2. CopyCode Button CSS

.code-header {
    display: flex;
    justify-content: flex-end;
  }

.copy-code-button {
  position: absolute;
  display: grid;
  grid-auto-flow: column;
  align-items: center;
  grid-column-gap: 4px;
  border: none;
  cursor: pointer;
  border: 1px solid #8f8f8f;
  border-radius: 0.2rem;
  background-color: #e9e9e9;
  font-size: 0.8rem;
  padding: 0px 4px;
}
.copy-code-button::before {
  content: "Copy";
}

.copy-code-button::after {
  content: "📋";
  display: block;
}

.copied::before {
    content: "Copied!";
  }

.copied::after {
  content: "✔️";
}

3. CopyCode Button JS

function initCopyCode(){
  const codeBlocks = document.querySelectorAll("code");
  codeBlocks.forEach((codePre, index) => {
    divCopyCode = document.createElement("div");
    divCopyCode.classList.add('code-header');
    divCopyCode.innerHTML = "<button class=\"copy-code-button\" aria-label=\"Copy code to clipboard\"></button>";
    codeBlocks[index].prepend(divCopyCode);
  });
  
  const copyCodeButtons = document.querySelectorAll('.copy-code-button');
  
  copyCodeButtons.forEach((copyCodeButton, index) => {    
      const code = codeBlocks[index].innerText;
      copyCodeButton.addEventListener('click', () => {
          window.navigator.clipboard.writeText(code);
          copyCodeButton.classList.add('copied');

          setTimeout(() => {
          copyCodeButton.classList.remove('copied');
          }, 2000);
      });
  });
}

4. Apply to HTML

...
  </body>
  <script>
        initCopyCode();
  </script>
</html>
This page was generated by GitHub Pages.
Author. silentjini