diff options
| author | Alexander Dunkel <13646666+Sieboldianus@users.noreply.github.com> | 2019-08-18 16:27:31 +0200 |
|---|---|---|
| committer | Track3 <34504964+Track3@users.noreply.github.com> | 2019-08-18 22:27:31 +0800 |
| commit | 16c9d78ae518aebb65c3bca5871b2550bbabca16 (patch) | |
| tree | 6788f55696b07bb38ba9f3b82ebb2bfc1dfa737c /assets/js/code-copy.js | |
| parent | a9f2ddcfa9f9c5ba93902995162c268f860c1750 (diff) | |
| download | hermit-16c9d78ae518aebb65c3bca5871b2550bbabca16.tar.gz | |
Add code copy button to all code fields in the blog (#81)
Diffstat (limited to 'assets/js/code-copy.js')
| -rw-r--r-- | assets/js/code-copy.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/assets/js/code-copy.js b/assets/js/code-copy.js new file mode 100644 index 0000000..68036c8 --- /dev/null +++ b/assets/js/code-copy.js @@ -0,0 +1,56 @@ +/** + * Utils + */ + +// Add code-copy buttons using progressive enhancement +// © 2019. Tom Spencer +// https://www.fiznool.com/blog/2018/09/14/adding-click-to-copy-buttons-to-a-hugo-powered-blog/ +(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); +})(); |
