add buttons to copy code block contents

Adds a clickable "copy" link in the top-right corner of each code block.

If available, uses the navigator.clipboard API. Falls back to selecting
the text and calling document.execCommand('copy') to copy text.
This commit is contained in:
Kian Kasad
2021-04-03 18:24:39 -07:00
parent 0f4dc88c63
commit 4425e21596
2 changed files with 48 additions and 1 deletions

View File

@@ -96,3 +96,34 @@
</script>
{{- end }}
{{- if (not .Site.Params.disableCodeCopy) }}
<script>
document.querySelectorAll('pre > code').forEach((codeblock) => {
const container = codeblock.parentNode.parentNode;
const copybutton = document.createElement('div');
copybutton.classList.add('copy-code');
copybutton.innerHTML = 'copy';
copybutton.addEventListener('click', (cb) => {
if ('clipboard' in navigator) {
navigator.clipboard.writeText(codeblock.textContent);
return;
}
const range = document.createRange();
range.selectNodeContents(codeblock);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
try {
document.execCommand('copy');
} catch (e) {};
selection.removeRange(range);
});
container.appendChild(copybutton);
});
</script>
{{- end }}