Buttons for Copying Codes

 A couple of days ago I posted a way to add a copy button to a single code post. Now I have redesigned for pages with multiple codes posted so that any number of individual buttons can be added, one per code section. I have added it to my theme HTML, but the script would also work in an individual post HTML.

Here is the script and accompanying tags:




<dialog id="feedback">&#160;</dialog>
<script>
//<![CDATA[
function copyCode(button) {
  const container = button.closest('div');
  const targettedTag = container.querySelector('code');
  if (targettedTag) {
    const textToCopy = targettedTag.innerText;
    navigator.clipboard.writeText(textToCopy);
    const dialog = document.getElementById('feedback');
    dialog.innerHTML = 'Code copied to clipboard.<br><br><button style="float:right" onclick="window.feedback.close();">Close</button>';
    dialog.showModal();
  }
}
//]]>
</script>

To use this in a post, when in HTML mode, just wrap the code being posted like this:




<div>
<button onclick="copyCode(this)" style="float:right">&#128203;</button><br>
<pre><code>THE_CODE_GOES_HERE</code></pre>
</div>


That will provide the copy button with the published post.

To add this to the theme HTML for using with multiple posts is not that hard. I put the script into an includable and called it from the post includable, just before the end, right after this:


<b:include data='post' name='postFooter'/>

<!-- added -->
<b:if cond='data:view.isSingleItem and not data:view.isPage'>
<b:include name='copycode'/>
</b:if>


Then, to make the includable, just put the script between the appropriate tags, like:




<b:includable id='copycode'>
<!-- THE_SCRIPT_AND_DIALOG_TAGS_HERE -->
</b:includable>


and then put that in place before the next includable in the theme.


Be sure to back up your theme!

 

Comments (3)