mirror of
https://github.com/snachodog/just-the-docs.git
synced 2025-09-12 21:03:32 -06:00
Add copy code button to code snippets (#945)
Hello everyone, this is my implementation for the copy button on the snippet (requested in #924) The implementation is made 100% javascript as with or without a jekyll template modification you still have to execute some javascript code, and I consider it the best choice. the button only appears if the mouse is over it, to allow the entire line to be read the important CSS changes were made to make the copy button work even in the long code situation:  to avoid this:  Co-authored-by: Matt Wang <matt@matthewwang.me>
This commit is contained in:
@@ -479,6 +479,47 @@ jtd.onReady(function(){
|
||||
scrollNav();
|
||||
});
|
||||
|
||||
// Copy button on code
|
||||
|
||||
|
||||
{%- if site.enable_copy_code_button != false %}
|
||||
|
||||
jtd.onReady(function(){
|
||||
|
||||
var codeBlocks = document.querySelectorAll('div.highlighter-rouge, div.listingblock, figure.highlight');
|
||||
|
||||
var svgCopied = '<svg viewBox="0 0 24 24" class="copy-icon"><use xlink:href="#svg-copied"></use></svg>';
|
||||
var svgCopy = '<svg viewBox="0 0 24 24" class="copy-icon"><use xlink:href="#svg-copy"></use></svg>';
|
||||
|
||||
codeBlocks.forEach(codeBlock => {
|
||||
var copyButton = document.createElement('button');
|
||||
var timeout = null;
|
||||
copyButton.type = 'button';
|
||||
copyButton.ariaLabel = 'Copy code to clipboard';
|
||||
copyButton.innerHTML = svgCopy;
|
||||
codeBlock.append(copyButton);
|
||||
|
||||
copyButton.addEventListener('click', function () {
|
||||
if(timeout === null) {
|
||||
var code = codeBlock.querySelector('code').innerText.trim();
|
||||
window.navigator.clipboard.writeText(code);
|
||||
|
||||
copyButton.innerHTML = svgCopied;
|
||||
|
||||
var timeoutSetting = 4000;
|
||||
|
||||
timeout = setTimeout(function () {
|
||||
copyButton.innerHTML = svgCopy;
|
||||
timeout = null;
|
||||
}, timeoutSetting);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
{%- endif %}
|
||||
|
||||
})(window.jtd = window.jtd || {});
|
||||
|
||||
{% include js/custom.js %}
|
||||
|
Reference in New Issue
Block a user