How to add a copy pre-content codebox to a blogger post

This post is very important for us if we want to publish code on the Blogger website.

How to add a copy pre-content codebox to a blogger post

We will complete this task today through these three steps.

To complete this task, we need to go to the dashboard of your Blogger website.

Click the Theme and click on Edit HTML.

Copy the CSS codes below.

Then place them in your Blogger template where CSS is used.

  
.code-box {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
  overflow: auto;
  font-family: 'Courier New', Courier, monospace;
}

/* Copy button */
.copy-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
}

/* Button hover effect */
.copy-button:hover {
  background: #0056b3;
}
  

Now copy the following JavaScript code and place it above the closing body tag of your Blogger template.

  
// Add copy button dynamically to each code box
  document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.code-box').forEach(function(codeBox) {
      const button = document.createElement('button');
      button.classList.add('copy-button');
      button.innerText = 'Copy';
      codeBox.appendChild(button);

      button.addEventListener('click', function() {
        const code = codeBox.querySelector('code').innerText;

        // Copy the code to clipboard
        navigator.clipboard.writeText(code).then(() => {
          button.innerText = 'Copied!';
          setTimeout(() => (button.innerText = 'Copy'), 2000);
        }).catch(() => {
          button.innerText = 'Failed!';
          setTimeout(() => (button.innerText = 'Copy'), 2000);
        });
      });
codeBox.addEventListener('dblclick', function() {
  const code = codeBox.querySelector('code').innerText;

  // Copy the code to clipboard
  navigator.clipboard.writeText(code).then(() => {
    alert('Code copied to clipboard!');
  });
});
    });
  });
  

Then save.

Now, place the following codes in the Blogger post or page where you want to preview the codes nicely.

Of course, you need to place your codes inside the Blogger page or post via HTML view.

  
<pre class="code-box">
  <code>
Your_Code_Here
  </code>
</pre>
  

You should parse the code you posted.

Click here for Parser.

Place the parsed codes in Your_Code_Here.

Then you publish your page or post.

See your desired work done.

If there is any problem to understand, contact us on Telegram

Next Post Previous Post
No Comment
Add Comment
comment url