Skip to content

Commit 82b9b83

Browse files
Add copy button to code blocks for improved documentation usability
1 parent 365d409 commit 82b9b83

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

docs_theme/css/copy-button.css

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
.copy-block-button {
2+
position: absolute;
3+
top: 6px;
4+
right: 6px;
5+
font-size: 12px;
6+
padding: 2px 6px;
7+
cursor: pointer;
8+
9+
background: #f7f7f9; /* code block bg */
10+
border: 1px solid #e1e1e8; /* code block border */
11+
border-radius: 3px;
12+
13+
color: #dc322f !important; /* fallback if no span */
14+
15+
box-shadow: 0 1px 1px rgba(0,0,0,0.04);
16+
}
17+
18+
/* Separate rule for the span inside the button */
19+
.copy-block-button span {
20+
color: #dc322f !important;
21+
}

docs_theme/js/copy-button.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
document.addEventListener("DOMContentLoaded", function () {
2+
document.querySelectorAll("pre > code").forEach(function (codeBlock) {
3+
const button = document.createElement("button");
4+
button.className = "copy-block-button";
5+
button.type = "button";
6+
button.textContent = "Copy";
7+
8+
button.addEventListener("click", function () {
9+
navigator.clipboard.writeText(codeBlock.textContent).then(function () {
10+
button.textContent = "Copied!";
11+
setTimeout(() => button.textContent = "Copy", 1200);
12+
});
13+
});
14+
15+
const pre = codeBlock.parentNode;
16+
pre.style.position = "relative";
17+
pre.appendChild(button);
18+
});
19+
});

docs_theme/main.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
<link href="{{ 'css/bootstrap.css'|url }}" rel="stylesheet">
1717
<link href="{{ 'css/bootstrap-responsive.css'|url }}" rel="stylesheet">
1818
<link href="{{ 'css/default.css'|url }}" rel="stylesheet">
19+
{% for path in config.extra_css %}
20+
<link href="{{ path|url }}" rel="stylesheet">
21+
{% endfor %}
1922

2023

2124
<script type="text/javascript">

mkdocs.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,9 @@ nav:
8787
- 'Mozilla Grant': 'community/mozilla-grant.md'
8888
- 'Funding': 'community/funding.md'
8989
- 'Jobs': 'community/jobs.md'
90+
91+
extra_css:
92+
- css/copy-button.css
93+
94+
extra_javascript:
95+
- js/copy-button.js

0 commit comments

Comments
 (0)