Add Copy to clipboard button to each highlight code with JavaScript

Hi, maybe you already know this but what I found after a lot of struggle is worth sharing with others. How to add ‘Copy to clipboard’ button into Hugo’s built-in code highlighter - pygment - just solved in a few lines of JS without any library.

// copy to clipboard
const d = document;
const tempCopyInput = d.createElement('input');
d.body.appendChild(tempCopyInput);
tempCopyInput.style.position = 'fixed';
tempCopyInput.style.top = '-1000px';
// copy to clipboard function
const copyToCB = () => {
  tempCopyInput.select();
  d.execCommand('copy');
};

// Hugo outputs code `div` with `highlight` class name.
// copy from highlight container
let highlight = d.querySelectorAll('.highlight'),// or any div containing code stuff
    copyIcon = d.createElement('button');
copyIcon.innerHTML = 'copy to clipboard';
  
highlight.forEach((hl) => {
  hl.appendChild(copyIcon.cloneNode([true]));
  hl.children[1].addEventListener('click',() => {
  let codeText = hl.childNodes[0].textContent;
  tempCopyInput.setAttribute('value', codeText);
    copyToCB();
  })

})

I’m not a good at JavaScript so any suggestion will be appreciated.
TY!

1 Like