Copy code button
A small copy button for your code blocks. Out of the way until you need it, one click when you do.1
The button sits in the top corner of every code block. On a computer it shows up when you hover the code, on phones and tablets it's always visible. After a click it says "Copied" for a moment, then goes back to "Copy".
Preview
Here's one to try it on:
console.log("Hello, Bear!");
How to use
- Copy the script below and paste it into your footer directive (Dashboard → Settings → Header and footer directives).
- Copy the styles and add them to your theme.
Script
<script>
/* Copy code button | robertbirming.com */
(() => {
if (!navigator.clipboard) return;
document.querySelectorAll("main pre").forEach((pre) => {
const wrap = document.createElement("div");
wrap.className = "code-wrap";
pre.before(wrap);
const button = document.createElement("button");
button.type = "button";
button.className = "copy-code";
button.textContent = "Copy";
wrap.append(pre, button);
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(pre.innerText.trimEnd());
button.textContent = "Copied";
button.classList.add("is-copied");
} catch {
button.textContent = "Failed";
}
setTimeout(() => {
button.textContent = "Copy";
button.classList.remove("is-copied");
}, 1500);
});
});
})();
</script>
Styles
/* Copy code button | robertbirming.com */
.code-wrap {
position: relative;
}
.copy-code {
position: absolute;
inset-block-start: 0.5em;
inset-inline-end: 0.5em;
padding: 0.2em 0.6em;
font: inherit;
font-size: 0.8em;
color: color-mix(in srgb, var(--text-color), transparent 40%);
background-color: var(--background-color);
border: 1px solid color-mix(in srgb, var(--text-color), transparent 80%);
border-radius: 4px;
cursor: pointer;
opacity: 0;
transition: opacity 150ms ease, color 150ms ease;
}
.code-wrap:hover .copy-code,
.copy-code:focus-visible,
.copy-code.is-copied {
opacity: 1;
}
@media (hover: none) {
.copy-code {
opacity: 1;
}
}
@media (hover: hover) {
.copy-code:hover {
color: var(--text-color);
}
}
.copy-code.is-copied {
color: var(--link-color);
}
@media (prefers-reduced-motion: reduce) {
.copy-code {
transition: none;
}
}
Happy blogging, and happy copying.
Want more? Check out the full Bear Blog library.
Requires JavaScript, available on Bear Blog's premium plan.↩