Edit in JSFiddle

  document.addEventListener("DOMContentLoaded", function () {
    var copyButtons = document.querySelectorAll('.code-copy-btn');
    
    copyButtons.forEach(function (button) {
      button.addEventListener('click', function () {
        var codeText = button.previousElementSibling.textContent;
        navigator.clipboard.writeText(codeText).then(function () {
          button.textContent = 'Copied!';
          setTimeout(function () {
            button.textContent = 'Copy';
          }, 2000);
        }).catch(function (error) {
          console.error('Failed to copy text: ', error);
        });
      });
    });
  });
<div class="code-container">
  <div class="code-box">
    <pre class="code-text">
      function helloWorld() {
        console.log("Hello, world!");
      }
    </pre>
    <button class="code-copy-btn">Copy</button>
  </div>


  <div class="code-box">
    <pre class="code-text">
      function exampleFunction() {
        alert("This is an example function.");
      }
    </pre>
    <button class="code-copy-btn">Copy</button>
  </div>
</div>
   .code-container {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      min-height: 100vh;
      background-color: #f0f0f0;
    }

    .code-box {
      width: 50%;
      max-width: 600px; /* ブログの幅に合わせて調整 */
      margin: 10px;
      background-color: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      overflow: hidden;
      position: relative;
    }

    .code-text {
      padding: 10px;
      font-size: 14px;
    }
    
    .code-copy-btn {
      background-color: #007bff;
      color: #fff;
      border: none;
      padding: 5px 10px;
      border-radius: 0 0 5px 5px;
      cursor: pointer;
      position: absolute;
      top: 0;
      right: 0;
    }
    
    .code-copy-btn:hover {
      background-color: #0056b3;
    }