From 48d2a3bc9aea5057ba54cbb5ed1313533619af89 Mon Sep 17 00:00:00 2001 From: "Em (Ethan) Ruszanowski" Date: Tue, 24 Oct 2023 16:11:51 -0400 Subject: [PATCH] Add code block copy button. --- _config.yml | 3 +++ assets/js/clipboard.js | 47 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 assets/js/clipboard.js diff --git a/_config.yml b/_config.yml index 41dcd24..bbc4b99 100644 --- a/_config.yml +++ b/_config.yml @@ -84,6 +84,9 @@ footer: icon: "fab fa-fw fa-github" url: "https://github.com/ethanrusz" +after_footer_scripts: + - assets/js/clipboard.js + social: type: names: diff --git a/assets/js/clipboard.js b/assets/js/clipboard.js new file mode 100644 index 0000000..7febb0f --- /dev/null +++ b/assets/js/clipboard.js @@ -0,0 +1,47 @@ +/* + * A nice little clipboard script provided by crykn. Thanks! + */ + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function onClickEffect(btn, style) { + btn.removeClass("btn-light"); + btn.addClass(style); + await sleep(250); + btn.removeClass(style); + btn.addClass("btn-light"); +} + +$(document).ready(function() { + // Create butons + $(".page__content pre > code").each(function() { + $(this).parent().prepend( + $(document.createElement('button')).prop({ + type: 'button', + innerHTML: '', + }) + .attr('title', 'Copy to clipboard') + .addClass('btn') + .addClass('btn--primary') + .css('position', 'absolute') + .css('right', '1em') + // Click listener + .on('click', function() { + let codeElement = $(this).parent().children('code').first(); + + if (!codeElement) { + throw new Error("Unexpected error! No corresponding code block was found for this button."); + } + + // Blink effect + onClickEffect($(this), "btn--success") + + // Copy to clipoard function + navigator.clipboard.writeText($(codeElement).text()).then(() => true, () => true); + return true; + }) + ); + }); +});