Add copy button to code blocks for improved documentation usability

This commit is contained in:
Shrikant Giri 2025-11-21 15:14:21 +05:30
parent 365d409adb
commit 82b9b83ca4
4 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,21 @@
.copy-block-button {
position: absolute;
top: 6px;
right: 6px;
font-size: 12px;
padding: 2px 6px;
cursor: pointer;
background: #f7f7f9; /* code block bg */
border: 1px solid #e1e1e8; /* code block border */
border-radius: 3px;
color: #dc322f !important; /* fallback if no span */
box-shadow: 0 1px 1px rgba(0,0,0,0.04);
}
/* Separate rule for the span inside the button */
.copy-block-button span {
color: #dc322f !important;
}

View File

@ -0,0 +1,19 @@
document.addEventListener("DOMContentLoaded", function () {
document.querySelectorAll("pre > code").forEach(function (codeBlock) {
const button = document.createElement("button");
button.className = "copy-block-button";
button.type = "button";
button.textContent = "Copy";
button.addEventListener("click", function () {
navigator.clipboard.writeText(codeBlock.textContent).then(function () {
button.textContent = "Copied!";
setTimeout(() => button.textContent = "Copy", 1200);
});
});
const pre = codeBlock.parentNode;
pre.style.position = "relative";
pre.appendChild(button);
});
});

View File

@ -16,6 +16,9 @@
<link href="{{ 'css/bootstrap.css'|url }}" rel="stylesheet">
<link href="{{ 'css/bootstrap-responsive.css'|url }}" rel="stylesheet">
<link href="{{ 'css/default.css'|url }}" rel="stylesheet">
{% for path in config.extra_css %}
<link href="{{ path|url }}" rel="stylesheet">
{% endfor %}
<script type="text/javascript">

View File

@ -87,3 +87,9 @@ nav:
- 'Mozilla Grant': 'community/mozilla-grant.md'
- 'Funding': 'community/funding.md'
- 'Jobs': 'community/jobs.md'
extra_css:
- css/copy-button.css
extra_javascript:
- js/copy-button.js