Monday, September 15, 2025

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

  • Your Blogger template already uses Google Code Prettify (you've included the Prettify script and CSS in your template).
  • Basic knowledge of editing Blogger templates (don't worry, I'll walk you through each step!).
  • Access to your Blogger dashboard to modify the template.

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:

  • Styles code blocks with a white background, rounded corners, and a border.
  • Positions the copy button in the top-right corner.
  • Uses Blogger theme variables ($(link.color), $(mobile.button.color), $(link.hover.color)) to match your blog's color scheme.
  • Adds a "Copied!" popup when the code is copied.

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:

  • Waits for the page to load (DOMContentLoaded).
  • Finds all <pre class="prettyprint"> elements.
  • Adds a "Copy" button to each code block.
  • Copies only the code content (excluding the button's text) when clicked.
  • Shows a "Copied!" confirmation for 2 seconds.

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

  • Button Not Appearing: Ensure the Google Code Prettify script and CSS are included in your template's <head>:
<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'/>
  • Inconsistent Styling: If code blocks look different on archive or post pages, double-check that the CSS is within the <b:skin> section and not overridden by other styles. You can add !important to critical styles (e.g., background-color: #ffffff !important) if needed.
  • Copy Includes "Copy" Text: If the copied text includes the word "Copy," ensure you're using the exact JavaScript code above, which excludes the button's text.
  • Button Styling Issues: If the button's colors don't match your theme, replace $(link.color) and $(mobile.button.color) with specific colors (e.g., #dd7700 for the button background, #ffffff for text).

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! 🚀

No comments:

Post a Comment

Building BlueMountainDJ.com: A Modern Wedding DJ Website with Tailwind CSS and JavaScript

Building BlueMountainDJ.com: A Modern Wedding DJ Website with Tailwind CSS and JavaScript As a web developer, I recently had the opportunit...