Button to copy code on your page

When you follow my guides here, you will have seen that I have some fields in which there are code snippets. In these fields I have made it possible to click on a button and copy the contents of the field when you hover over the field, or on mobiles click on it. You can see an example here:

<?php

                $frags = [];
                $commaChance = .33;
                while(true) {
                    $nwords = random_int(3, 15);
                    $words = self::random_values(self::$lorem, $nwords);
                    $frags[] = implode(' ', $words);
                    if(self::random_float() >= $commaChance) {
                        break;
                    }
                    $commaChance /= 2;
                }

I want to share this feature with you. Det kan benyttes på alle sider hvor du benytter tags. I WordPress er det blot at vælge indlejret kode, så vil de være formateret som .
The code I will share with you you need to insert on the pages you want the function to be active on. I have WordPress and want to use it everywhere, so I’ve made it insert into wp_head as an action.

If you use WordPress , make sure you have a child theme if you follow this exactly.

How to set up copy code

Open the file functions.php in your theme (child theme) and at the bottom of this file insert the following:

add_action( "wp_head", "wcioCopyCode", 10 );

function wcioCopyCode() {
?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {

            // Button html used to display the button and remove the code from the copied text.
            var btnHtml= '<button class="wcioCopyCodeBtn">copy</button>';

            // When clicking the button, run this code
            $("code").on("click", ".wcioCopyCodeBtn", function() {

                // Setup some variables
                var $temp = $("<textarea>");
                var regex = /<br\s*[\/]?>/gi;

                // Replace <br> (newline in html) with \n (newline in text) to make sure multiple lines work.
                var encodedStr = $(this).parent().html().replace(regex, "\n").replace(btnHtml, "");

                // Add a tmp element to store the content (textarea to work with multiple line) and then select / copy content before removing it.
                $(this).parent().append($temp);
                $temp.html(encodedStr).select();
                document.execCommand("copy");
                $temp.remove();

                // Change the text to a green copied one.
                var self = this;
                self.innerHTML = '<span style="color:#3fb950">&#10003; copied</span>';

                // Change the button content back after X amount of seoncds.
                setTimeout(function() {
                    self.innerHTML = 'copy';
                }, 2000);

               });

            // Add the button html to all code tags
            jQuery( "code" ).append(  btnHtml );


        });
    </script>

    <style>
    .wcioCopyCodeBtn {
         opacity: 0;
         background-color: #282e33;
         border-color: #6e7681;
         border: 1px solid #ececec;
         padding: 6px 6px;
         border-radius: 5px;
         cursor: pointer;
         text-align: center;
         margin: 0px auto;
         display: inline-flex;
         margin-left:4px;
         vertical-align: middle;
         position: absolute;
         right: 5px;
         top: 5px;
         transition: opacity 1s;
    }
     .wcioCopyCodeBtn:hover {
         background-color: #282e33;
         border-color: #6e7681;
         border: 1px solid #ececec;
         color:#fff;
    }
     code:hover .wcioCopyCodeBtn {
         opacity:1;
    }
     code {
         position: relative;
         background: #ececec;
         border-radius: 5px;
         padding: 11px 10px 12px 4px !important;
         display: block;
    }
    </style>
<?php
}

Once you have entered it, save the file and look at your page. You should now be able to mouse over or click on your mobile and see a button that says “Copy” and when you click it will say “Copied”. There is a bit of CSS included in the code (in the <style>CSS</style> part), you may want to put that in your theme’s CSS file instead.

Unlike some of these COPY code functions, the one I’ve put together here works with line breaks (using textarea) or doesn’t change things like <?php to &x3C;?php like I’ve seen others do. This is achieved by converting to html before pasting into the texarea field.

You have now given your visitors the ability to copy code or anything else you put in a code tag.

close

Få mine tips direkte i din indbakke

Tilmeld dig for at modtage mit nyhedsbrev og hold dig opdateret med det nyeste herfra.

Vi spammer ikke! Læs vores privatlivspolitik hvis du vil vide mere.

Leave a Comment