js: Define function for copy to clipboard and provide it in onClick

Instead of looping through all the code blocks at onload, just put an
onClick tag in the HTML template, which calls a global function.

This also improves the semantics since we aren't abusing href to be
javascript.

Also improves the writeText function call, since that method actually
returns a Promise which we should be waiting on. It technically worked
before because Promise starts executing instantly in JS, without being
awaited.
This commit is contained in:
2026-09-18 14:21:47 -05:00
parent a2a8e2c205
commit b67e3f4671
2 changed files with 20 additions and 22 deletions
+8 -11
View File
@@ -1,9 +1,8 @@
// code block copy to clipboard // code block copy to clipboard
window.onload = () => { async function copy_to_clipboard(button) {
document.querySelectorAll(".code-block").forEach(codeBlock => { const codeBlock = button.parentElement.parentElement;
const button = codeBlock.querySelector(".code-header > .code-copy-button");
// lang will not be unset because we default it to text // lang will not be unset because we default it to textoriginalCopyText
// clone it so it doesn't change the actual DOM element // clone it so it doesn't change the actual DOM element
const codeElem = codeBlock.querySelector("code[data-lang]").cloneNode(true); const codeElem = codeBlock.querySelector("code[data-lang]").cloneNode(true);
// bashsession: remove command output lines // bashsession: remove command output lines
@@ -12,14 +11,12 @@ window.onload = () => {
codeElem.querySelectorAll(".gp").forEach(e => e.parentNode.removeChild(e)); codeElem.querySelectorAll(".gp").forEach(e => e.parentNode.removeChild(e));
const rawCode = codeElem.innerText; const rawCode = codeElem.innerText;
const originalCopyText = button.innerHTML; await navigator.clipboard.writeText(rawCode);
button.onclick = event => {
navigator.clipboard.writeText(rawCode);
// TODO: maybe we could add a fancier indicator, like a flash or something // TODO: maybe we could add a fancier indicator, like a flash or something
event.target.innerHTML = "Copied!"; const originalCopyText = button.innerHTML;
button.innerHTML = "Copied!";
setTimeout(() => { setTimeout(() => {
event.target.innerHTML = originalCopyText; button.innerHTML = originalCopyText;
}, 3000); }, 3000);
} }
});
}
+2 -1
View File
@@ -5,7 +5,8 @@
<div class="code-block"> <div class="code-block">
<div class="code-block-header"> <div class="code-block-header">
<pre class="code-block-type">{{ $type }}</pre> <pre class="code-block-type">{{ $type }}</pre>
<a href="javascript:void(0)" class="code-block-copy-button"> {{/* https://blog.udemy.com/javascript-href/ */}}
<a href="javascript:null" onClick="javascript:copy_to_clipboard(this)" class="code-block-copy-button">
{{ i18n "copy_to_clipboard" }} {{ i18n "copy_to_clipboard" }}
</a> </a>
</div> </div>