Diego De La Puente

Clipboard Functionality for Code Blocks

1. Overview

This functionality allows users to copy the contents of a code block to their clipboard by clicking a "Copy" button. When the button is clicked, it temporarily changes to "Copied" to indicate success.

2. Including Clipboard.js

To enable clipboard functionality, you need to include the Clipboard.js library. This library provides a simple way to copy text to the clipboard.

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
<script src="../../js/clipboard.js"></script>

clipboard.min.js from CDN: This line includes the Clipboard.js library itself, which provides the core functionality for copying text to the clipboard. It handles the actual clipboard interaction and provides the ClipboardJS object that your code will use.

Your clipboard.js: This is your custom script that initializes the Clipboard.js functionality on your page. It contains your specific logic for binding the Clipboard.js to the elements on your page and providing the necessary feedback to the user (e.g., changing button text to "Copied" after a successful copy).

Detailed Explanation:

  • Clipboard.js Library (clipboard.min.js from CDN)
    • What It Does: This script is the Clipboard.js library itself. It contains all the functions and methods needed to perform clipboard operations, such as copying text.
    • Why You Need It: Without this script, you won't have access to the ClipboardJS constructor or any of the clipboard functions that make copying text possible. This is a third-party library that encapsulates the complexity of clipboard interactions across different browsers.
    • Standalone?: If you only include this script, you'll have access to the Clipboard.js functionality but no specific instructions on how to use it on your page. It's like having a toolbox without knowing what to do with the tools.
  • Your clipboard.js
    • What It Does: This script is where you configure how Clipboard.js interacts with your page. It initializes Clipboard.js, binds it to your buttons or other elements, and handles events like successful copying or errors.
    • Why You Need It: It provides the "glue" code that connects the Clipboard.js library to your HTML elements. It contains the specific logic for how and when to perform the clipboard operations on your page.
    • Standalone?: If you only include this script without including Clipboard.js, your custom script will fail because it relies on the ClipboardJS object provided by the Clipboard.js library. Your custom script doesn’t provide the core functionality—it only configures and uses it.

Analogous Example: Think of clipboard.min.js as a sophisticated toolset for copying text, while your clipboard.js script is the instructions on how to use these tools for your specific project. Without the toolset (Clipboard.js library), the instructions alone (your script) won’t work because the tools aren’t there. Without the instructions (your script), the toolset alone is not enough because it doesn’t know what you want to do with the tools.

3. Adding the Copy Button to a code block

Add a button with the class copy-btn and data-clipboard-target attribute to specify the target code block to copy (put this button code between your closing </pre> tag and closing code </div> for the "code-block":

<div class="code-toolbar">
    <button class="copy-btn" data-clipboard-target="#code-block">
        <span class="copy-text">Copy</span>
        <span class="copied-text">Copied</span>
    </button>
</div>

The button will change from "Copy" to "Copied" temporarily after being clicked, providing feedback to the user. This will sync up with your custom .js code at clipboard.js

4. Configuring Clipboard.js from CDN for Specific Page Usage

The following JavaScript sets up the clipboard functionality. It attaches to the copy-btn class and handles the copy operation:

// File: clipboard.js
document.addEventListener('DOMContentLoaded', function() {
    var clipboard = new ClipboardJS('.copy-btn', {
        target: function(trigger) {
            return trigger.parentElement.previousElementSibling.querySelector('code');
        }
    });

    clipboard.on('success', function(e) {
        e.clearSelection();
        var button = e.trigger;
        var copyText = button.querySelector('.copy-text');
        var copiedText = button.querySelector('.copied-text');

        // Show 'Copied!' and hide 'Copy'
        copyText.style.display = 'none';
        copiedText.style.display = 'inline';

        setTimeout(function() {
            // Reset to 'Copy' after a brief delay
            copyText.style.display = 'inline';
            copiedText.style.display = 'none';
        }, 2000); // Adjust timeout duration as needed
    });

    clipboard.on('error', function(e) {
        console.error('Failed to copy:', e);
        var feedbackElem = e.trigger.querySelector('.clipboard-feedback');
        if (feedbackElem) {
            feedbackElem.textContent = 'Copy failed. Please try again.';
            setTimeout(function() {
                feedbackElem.textContent = ''; // Clear feedback after a timeout
            }, 2000); // Adjust timeout duration as needed
        }
    });
});

This script initializes ClipboardJS library being loaded by the CND link and provides feedback to the user when the copy operation is successful or fails.

5. Example

Here's a complete example of a code block with the clipboard functionality, demonstrating an SQL SELECT statement:

<div class="code-block">
    <pre class="prettyprint"><code class="language-sql" id="example-code">
SELECT * 
FROM employees 
WHERE department = 'Sales';
</code></pre>
    <div class="code-toolbar">
        <button class="copy-btn" data-clipboard-target="#example-code">
            <span class="copy-text">Copy</span>
            <span class="copied-text">Copied</span>
        </button>
    </div>
</div>

The example demonstrates a code block with a "Copy" button that uses ClipboardJS to copy the SQL query's contents to the clipboard. Again notice how the standard <div class="code-block"> has a nested <div class="code-toolbar"> with the button HTML that calls on the connected JavaScript functionality.

6. Funky Behavior

Sometimes, when you copy the contents of a code block, you might notice an empty line at the beginning and end when pasting the copied contents. To eliminate the empty line at the top of the copied code block when pasting into a code editor, you can adjust the structure of your HTML slightly. The empty line is likely caused by the whitespace before the <code> tag in your current structure. Basically do not leave empty white space before and after the contents of your code block, immediately after your last character of code contents (lets say Java or Perl or HTML, etc) put a closing </code> and do not leave any white space.