Add copy content links to my code snippets

Many blogs are like this one, where they contain a few code snippets that readers might want to copy to their clipboard to re-use somewhere else.

This article describes a custom HTML gadget that will automatically add the material design icon as a copy-to-clipboard link, for any <code> tags in the content.

Note: This gadget assumes that all the code tags have a relatively-positioned container. In this blog, all the <code> tags are nested in <pre> tags, which are relatively positioned.

Material Design font

While Blogger's new templates feature a range of the material design icons, they don't offer all of them - the Material icons guide notes that you can massively reduce the size of the SVG by only using the ones you need.

The web-font does weigh in at ~56KB, but you user will benefit from it being cached by any other website they have visited that also uses the font.

<link href=''
      rel='stylesheet' />

The custom HTML gadget

  // Load Clipboard if we haven't already got it.
window.setTimeout(function() {
  if (typeof Clipboard !== 'undefined') {
  var s = document.createElement('script');
  s.src = '';
}, 500);
window.setTimeout(function() {
  if (typeof Clipboard === 'undefined' || !Clipboard) {
  var codes = document.querySelectorAll('code');
  if (!codes || codes.length < 1) return;
  // Load material font.
  var l = document.createElement('link');
  l.rel = 'stylesheet';
  l.href = '';
  // Add copy-to-clipboard links.
    .forEach(c => {
      var copyLink = document.createElement('div');
      copyLink.setAttribute('class', 'copy');
      copyLink.innerHTML = '&#xE14D;';
      copyLink.title = 
          _WidgetManager._GetAllData().messages.copy || 'Copy';
      c.parentElement.insertBefore(copyLink, c);
      var clipboard = new Clipboard(copyLink, {
        text: function(trigger) {
          return c.innerText;
      clipboard.on('success', e => {
                || 'Copied to clipboard');
}, 3000);
  pre .copy {
    font-family: 'Material Icons';
    font-size: 24px;
    position: absolute;
    right: 0;
    margin: 8px;
    cursor: pointer;
  pre .copy:not(:hover) {
    opacity: 0.4;

Happy code-snippeting!


Popular posts from this blog

Add syntax highlighting to my Blog

Change my post timestamps to a custom format

Add snippets to the Emporio theme