Skip to content

Commit 6953658

Browse files
committed
Add copy to clipboard buttons to code blocks
Only load the JS on posts that actually have code blocks.
1 parent 0176694 commit 6953658

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

layouts/blog/single.html

+7
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,10 @@ <h1>{{ .Title }}</h1>
3737

3838
<div class="separator">
3939
{{ end }}
40+
41+
{{ define "js-extra" }}
42+
{{ if (findRE "class=\"highlight\"" .Content 1) }}
43+
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/2.7.0/clipboard-polyfill.promise.js" integrity="sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94=" crossorigin="anonymous"></script>
44+
<script src="/js/copy-code-button.js"></script>
45+
{{ end }}
46+
{{ end }}

static/css/post.css

+35
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,38 @@ h1 {
2424
text-align: right;
2525
width: 48%;
2626
}
27+
28+
.copy-code-button {
29+
color: #272822;
30+
background-color: #FFF;
31+
border-color: #272822;
32+
border: 2px solid;
33+
border-radius: 3px;
34+
35+
/* right-align */
36+
display: block;
37+
margin-left: auto;
38+
margin-right: 0;
39+
40+
/* for some reason, there is space between the button and the code block */
41+
margin-bottom: -10px;
42+
43+
padding: 3px 8px;
44+
font-size: 0.8em;
45+
}
46+
47+
.copy-code-button:hover {
48+
cursor: pointer;
49+
background-color: #F2F2F2;
50+
}
51+
52+
.copy-code-button:focus {
53+
/* avoid an ugly focus outline on click in Chrome, but darken the button
54+
for accessibility. https://stackoverflow.com/a/25298082/1481479 */
55+
background-color: #E6E6E6;
56+
outline: 0;
57+
}
58+
59+
.copy-code-button:active {
60+
background-color: #D9D9D9;
61+
}

static/js/copy-code-button.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
if (clipboard) {
2+
document.querySelectorAll('.highlight').forEach(function (codeBlock) {
3+
var button = document.createElement('button');
4+
5+
button.className = 'copy-code-button';
6+
button.type = 'button';
7+
button.innerText = 'Copy';
8+
9+
button.addEventListener('click', function () {
10+
clipboard.writeText(codeBlock.innerText).then(function () {
11+
/* Chrome doesn't seem to blur automatically, leaving the button
12+
in a focused state */
13+
button.blur();
14+
15+
button.innerText = 'Copied!';
16+
setTimeout(function () {
17+
button.innerText = 'Copy';
18+
}, 2000);
19+
}, function (error) {
20+
button.innerText = 'Error';
21+
});
22+
});
23+
24+
codeBlock.parentNode.insertBefore(button, codeBlock);
25+
});
26+
}

0 commit comments

Comments
 (0)