Skip to content

Code block - Adding a copy code icon #70947

@paaljoachim

Description

@paaljoachim

What problem does this address?

An example. I have a very long code snippet and it becomes difficult to copy the code.

What is your proposed solution?

Adding a copy code icon would be very beneficial.

Here is a quick example made with ChatGPT:

add_action('wp_footer', function () {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('pre code').forEach((block) => {
            const wrapper = block.parentElement;
            wrapper.style.position = 'relative';

            const button = document.createElement('button');
            button.innerText = 'Copy';
            button.style.position = 'absolute';
            button.style.top = '8px';
            button.style.right = '8px';
            button.style.padding = '4px 8px';
            button.style.fontSize = '12px';
            button.style.backgroundColor = '#0073aa';
            button.style.color = '#fff';
            button.style.border = 'none';
            button.style.borderRadius = '3px';
            button.style.cursor = 'pointer';
            button.style.zIndex = '10';

            wrapper.appendChild(button);

            button.addEventListener('click', () => {
                navigator.clipboard.writeText(block.innerText).then(() => {
                    button.innerText = 'Copied!';
                    setTimeout(() => {
                        button.innerText = 'Copy';
                    }, 2000);
                });
            });
        });
    });
    </script>
    <?php
});

I see that Github adds a copy/duplicate icon to the above code making it easier to copy the code. It would be great to have something similar in the Code block. Below is the frontend example of the above code that I added.

Image

@Mamaduka

Metadata

Metadata

Assignees

No one assigned

    Labels

    [Block] CodeAffects the Code Block[Status] BlockedUsed to indicate that a current effort isn't able to move forward[Type] EnhancementA suggestion for improvement.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions