website

Personal website
git clone https://github.com/michaelneuper/website.git
README | Files | Log | Refs

commit 13240654324d85a5fb2d9d867fed1debb05f62fd
parent 3fe922df23bd04590d748bd9a4862a08de1738cd
Author: Michael Neuper <michael@michaelneuper.com>
Date:   Mon, 30 Oct 2023 18:26:36 +0200

Add copy button to code blocks

Diffstat:
Mstatic/css/styles.css | 32++++++++++++++++++++++++++++++++
Astatic/js/script.js | 27+++++++++++++++++++++++++++
2 files changed, 59 insertions(+), 0 deletions(-)

diff --git a/static/css/styles.css b/static/css/styles.css @@ -46,6 +46,11 @@ color: var(--base1) !important; } + button.copyButton { + background-color: var(--base03); + color: var(--base1); + } + a:link { color: var(--blue); } @@ -121,6 +126,11 @@ color: var(--violet); } + button.copyButton { + background-color: var(--base3); + color: var(--base01); + } + header { background: var(--base3); border-bottom: 0px; @@ -161,3 +171,24 @@ padding: 5px; } } + +pre { + position: relative; +} + +button.copyButton { + position: absolute; + bottom: 5px; + right: 5px; + opacity: 0.7; + border: none; + padding: 5px 10px; + border-radius: 5px; + cursor: pointer; + font-size: 14px; + transition: opacity 0.3s; +} + +button.copyButton:hover { + opacity: 1; +} +\ No newline at end of file diff --git a/static/js/script.js b/static/js/script.js @@ -0,0 +1,26 @@ +// Add copy button to <pre> blocks +function addCopyButton() { + const codeBlocks = document.querySelectorAll('pre'); + codeBlocks.forEach((codeBlock) => { + const copyButton = document.createElement('button'); + copyButton.innerHTML = 'Copy'; + copyButton.classList.add('copyButton'); + copyButton.addEventListener('click', () => { + const textToCopy = codeBlock.innerText.trim(); + copyToClipboard(textToCopy); + }); + codeBlock.appendChild(copyButton); + }); +} + +function copyToClipboard(text) { + navigator.clipboard.writeText(text) + .then(() => { + console.log('Text copied to clipboard:', text); + }) + .catch(err => { + console.error('Failed to copy: ', err); + }); +} + +addCopyButton(); +\ No newline at end of file