Hugo Copy Button

Page content

I like Websites with the Copy Button for certain Snippets. Why not integrate into the own Blog ?

Folder, Copy JS Stuff

Change to Hugo Root Folder

mkdir -p static/js/

cat << 'EOF' > static/js/copy-code.js
(function() {
  'use strict';

  if(!document.queryCommandSupported('copy')) {
    return;
  }

  function flashCopyMessage(el, msg) {
    el.textContent = msg;
    setTimeout(function() {
      el.textContent = "Copy";
    }, 1000);
  }

  function selectText(node) {
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(node);
    selection.removeAllRanges();
    selection.addRange(range);
    return selection;
  }

  function addCopyButton(containerEl) {
    var copyBtn = document.createElement("button");
    copyBtn.className = "highlight-copy-btn";
    copyBtn.textContent = "Copy";

    var codeEl = containerEl.firstElementChild;
    copyBtn.addEventListener('click', function() {
      try {
        var selection = selectText(codeEl);
        document.execCommand('copy');
        selection.removeAllRanges();

        flashCopyMessage(copyBtn, 'Copied!')
      } catch(e) {
        console && console.log(e);
        flashCopyMessage(copyBtn, 'Failed :\'(')
      }
    });

    containerEl.appendChild(copyBtn);
  }

  // Add copy button to code blocks
  var highlightBlocks = document.getElementsByClassName('highlight');
  Array.prototype.forEach.call(highlightBlocks, addCopyButton);
})();
EOF

Update Header

vim themes/mainroad/layouts/partials/header.html

copy this Content here:

---> snip <---
</div>
<script defer language="javascript" type="text/javascript"  src="{{ "/js/copy-code.js" | urlize | relURL }}"></script>
</header>
---> snip <--
<script defer language="javascript" type="text/javascript"  src="{{ "/js/copy-code.js" | urlize | relURL }}"></script>

Update CSS

cat << 'EOF' >> themes/mainroad/assets/css/style.css

.highlight {
    position: relative;
}
.highlight pre {
    padding-right: 75px;
}
.highlight-copy-btn {
    position: absolute;
    top: 7px;
    right: 7px;
    border: 0;
    border-radius: 4px;
    padding: 1px;
    font-size: 0.7em;
    line-height: 1.8;
    color: #fff;
    background-color: #777;
    min-width: 55px;
    text-align: center;
}
.highlight-copy-btn:hover {
    background-color: #666;
}
EOF

sha256: 1502cdb41bec00cf090f41fa4613663fc8d3e83cb70b04007e798025df331ac9