Blogger: Copy Code Button for Google Code Prettify

How to Add a Copy Code Button to Google Code Prettify in Blogger

If you use Google Code Prettify to display code snippets on your Blogger blog, you might want to make it easier for your readers to copy the code with a single click. Adding a "Copy" button to each code block enhances user experience and makes your blog more professional. In this post, I'll guide you through the process of adding a copy button to your Google Code Prettify code blocks in a Blogger template. The button will appear in the top-right corner of each code block, and when clicked, it copies the code to the clipboard with a "Copied!" confirmation.

Prerequisites

Step-by-Step Guide

Step 1: Back Up Your Template

Before making changes to your Blogger template, always create a backup to avoid losing your work.

  1. Go to your Blogger Dashboard.
  2. Navigate to Template > Edit HTML.
  3. Click the Download Template button to save a copy of your current template.

Step 2: Add CSS for the Copy Button

We'll add CSS to style the code blocks and the copy button, ensuring a consistent look with rounded corners and a white background across all pages (homepage, archive, and posts).

  1. In the Blogger template editor (Template > Edit HTML), locate the <b:skin> section. It starts with <b:skin><![CDATA[ and ends with ]]></b:skin>.
  2. Just before the closing ]]></b:skin>, add the following CSS code:
/* Code Block Copy Button
----------------------------------------------- */
pre.prettyprint {
  position: relative;
  padding: 30px 10px 10px 10px; /* Top padding for button, consistent padding for content */
  background-color: #ffffff; /* White background */
  border: 1px solid #cccccc; /* Light gray border */
  border-radius: 5px; /* Rounded corners */
  overflow: auto; /* Handle long code lines */
  font-family: &apos;Courier New&apos;, Courier, monospace; /* Consistent code font */
  font-size: 14px; /* Readable font size */
}

.copy-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: $(link.color); /* Matches your theme&apos;s link color */
  color: $(mobile.button.color); /* Matches your theme&apos;s button text color */
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
  border-radius: 3px;
}

.copy-button:hover {
  background-color: $(link.hover.color); /* Matches your theme&apos;s hover color */
}

.copy-button.copied::after {
  content: &apos;Copied!&apos;;
  position: absolute;
  top: 5px;
  right: 30px;
  background-color: #333;
  color: #fff;
  padding: 2px 5px;
  border-radius: 3px;
  font-size: 10px;
}

This CSS:

Step 3: Add JavaScript for Copy Functionality

Next, we'll add JavaScript to dynamically insert the copy button into each code block and handle the copying process using the Clipboard API.

  1. In the template editor, find the closing </head> tag.
  2. Just before </head>, add the following JavaScript code:
<script type='text/javascript'>
//<![CDATA[
document.addEventListener('DOMContentLoaded', function() {
  // Find all <pre> elements with class 'prettyprint'
  const codeBlocks = document.querySelectorAll('pre.prettyprint');
  
  codeBlocks.forEach(function(pre) {
    // Create copy button
    const button = document.createElement('button');
    button.className = 'copy-button';
    button.textContent = 'Copy';
    
    // Add click event listener for copying
    button.addEventListener('click', function() {
      // Get the text content of the <code> element inside <pre>, or fallback to pre's text excluding the button
      let code = '';
      const codeElement = pre.querySelector('code');
      if (codeElement) {
        code = codeElement.textContent;
      } else {
        // Clone the pre element to avoid modifying the original
        const preClone = pre.cloneNode(true);
        // Remove the copy button from the clone
        const buttonInClone = preClone.querySelector('.copy-button');
        if (buttonInClone) {
          buttonInClone.remove();
        }
        code = preClone.textContent;
      }
      
      // Use Clipboard API to copy text
      navigator.clipboard.writeText(code).then(function() {
        // Show 'Copied!' feedback
        button.classList.add('copied');
        setTimeout(function() {
          button.classList.remove('copied');
        }, 2000); // Remove 'Copied!' after 2 seconds
      }).catch(function(err) {
        console.error('Failed to copy: ', err);
      });
    });
    
    // Append button to the <pre> element
    pre.appendChild(button);
  });
});
//]]>
</script>

This JavaScript:

Step 4: Save and Test

  1. Click Save in the Blogger template editor.
  2. Preview your blog to ensure the copy button appears in the top-right corner of each code block.
  3. Test the copy functionality by clicking the button on a code block. The code should copy to your clipboard without including the "Copy" text, and you should see a "Copied!" popup.
  4. Check the homepage, archive, and post pages to confirm consistent styling (white background, rounded corners).

Troubleshooting Tips

<link href='https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/prettify.css' rel='stylesheet'/>
<script src='https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js'/>

Example

Here's how a code block will look in your posts (assuming you use <pre class="prettyprint"> for your code):

<pre class="prettyprint lang-html">
function helloWorld() {
  console.log("Hello, World!");
}
</pre>

This will display with a white background, rounded corners, and a "Copy" button in the top-right corner. Clicking the button copies the code (function helloWorld() { console.log("Hello, World!"); }) to the clipboard.

Conclusion

Adding a copy button to your Google Code Prettify code blocks is a simple way to improve your blog's usability. With just a few lines of CSS and JavaScript, you can make your code snippets more accessible and give your blog a polished, professional look. Try it out, and let me know in the comments if you run into any issues or have questions!

Happy blogging! 🚀

Share on:

← Back Home