Last active
October 1, 2019 16:21
-
-
Save iaminamcom/86c8db246ac75063867043af86d21b95 to your computer and use it in GitHub Desktop.
Add 'copy to clipboard' button which works. Made speciically for Hugo code highlighter but after a little bit of modification works everywhere.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment