Sometimes it can be quite useful to copy a link to a specific heading in a blog post. This is how to add a copy to clipboard function to your headings with Javascript.

First we create a function for copying text to clipboard. To copy text, we:

  1. create an input field
  2. add our text to the input field
  3. select it
  4. run the copy command
  5. and get rid of the temporary element
function copy(text) {
  const tmpInput = document.createElement('input');
  tmpInput.value = text;
  tmpInput.style.opacity = '0';
  document.body.appendChild(tmpInput);
  tmpInput.select();
  tmpInput.setSelectionRange(0, 99999); /*For mobile devices*/
  document.execCommand('copy');
  document.body.removeChild(tmpInput);
}

Source: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

Now we need to go through our headings and add the copy event. I also added a tooltip.

window.addEventListener('load', () => {
  const scope = '.post-content';
  const copiable = 'h1,h2,h3';
  document
    .querySelector(scope)
    .querySelectorAll(copiable)
    .forEach(e => {
      if (!e.id) return;
      const tooltiptext = document.createElement('span');
      tooltiptext.innerText = 'Click to copy link';
      tooltiptext.className = 'tooltiptext';
      e.classList.add('tooltip');
      e.addEventListener('click', () => {
        copy(`${window.location.href}#${e.id}`);
        const prevText = tooltiptext.innerText;
        tooltiptext.innerText = 'Copied link!';
        setTimeout(() => {
          tooltiptext.innerText = prevText;
        }, 3000);
      });
      e.appendChild(tooltiptext);
    });
});

Finally add some styling to your tooltip:

.tooltip {
  position: relative;
}
.tooltip .tooltiptext {
  visibility: hidden;
  width: 140px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 100%;
  left: 0;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 13px;
  font-weight: normal;
  font-family: Roboto;
}
.tooltip .tooltiptext::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}

Try to copy this text!