Tuesday, May 7, 2019

Add a Copy Button to Code Blocks

MadCap has a blog post about adding a copy button to code blocks, found here.

Here's what I had to do to get it working:

Step 1: Download the clipboad javascript and put it in your Resources/Scripts folder:
https://github.com/zenorocha/clipboard.js/archive/master.zip

Step 2: Add this to the <head> section:
<script src="../../../Resources/Scripts/clipboard.min.js"></script>

Step 3: Before the final closing body tag (</body>), add this:
<script>new ClipboardJS('.cbtn');</script>

Note: I named the button is named cbtn.

Step 4: Enclose each code block like the following:
<div class="Code">
   <p class="Codeblock" id="t01">Here's my code block text.</p>
   <button class="cbtn" data-clipboard-action="copy" data-clipboard-target="#t01" MadCap:conditions="Default.ScreenOnly"> </button>
</div>

Note: The button class must match what you defined in step 3.
Note: The ID must be unique for each code block.
Note: I added the Default.ScreenOnly condition so that it doesn't appear in PDF/Word.

Step 5: Add the following to your CSS file:
div.Code
{
   position: relative;
   overflow-x: auto;
}
p.Codeblock + button
{
   position: absolute;
   bottom: 0;
   right: 0;
   width: 26px;
   height: 26px;
   margin-bottom: 6pt;
   background: url(/url/to/image/content-copy.png)
}

Note: I use an image for the button, defined in the CSS. If you don't want an image, you can just put the plain text "Copy" in the HTML in step 4.
Note: The positioning places the button at the bottom right corner of the div.

No comments:

Post a Comment