Skip to content

Commit 614f16f

Browse files
feat: add "Copy" code to clipboard
1 parent 1dc3a9f commit 614f16f

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed

_layouts/post.html

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
layout: default
33
---
4+
45
{% assign date = page.updated | default: page.date %}
56
<main class="container post" id="main" role="main">
67
<header class="post-header" role="header">
@@ -31,12 +32,38 @@ <h6 class="post-meta">
3132
document
3233
.querySelector('.post-content')
3334
.querySelectorAll('h1,h2,h3,h4,h5,h6')
34-
.forEach(function(heading) {
35+
.forEach(function (heading) {
3536
if (heading.id)
3637
heading.innerHTML =
3738
'<a href="#' + heading.id + '">' +
3839
heading.innerText +
3940
'<\/a>' +
4041
'<span class="anchor-icon">§<\/span>';
41-
});
42+
});
43+
</script>
44+
{% comment %}
45+
46+
<!-- Copy code to clipboard -->
47+
{% endcomment %}
48+
<script>
49+
document
50+
.querySelector('.post-content')
51+
.querySelectorAll('pre.highlight')
52+
.forEach(function (pre) {
53+
var button = document.createElement('button');
54+
var copyText = 'Copy';
55+
button.className = 'copy';
56+
button.type = 'button';
57+
button.ariaLabel = 'Copy code to clipboard';
58+
button.innerText = copyText;
59+
button.addEventListener('click', function () {
60+
var code = pre.querySelector('code').innerText.trim();
61+
navigator.clipboard.writeText(code);
62+
button.innerText = 'Copied';
63+
setTimeout(function () {
64+
button.innerText = copyText;
65+
}, 4000);
66+
});
67+
pre.appendChild(button);
68+
});
4269
</script>

_sass/_code.scss

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
/**
1111
* Codeblock.
1212
*/
13-
pre {
13+
pre.highlight {
1414
padding: 8px 12px;
15+
position: relative;
1516

1617
// override skeleton styles
1718
> code {
@@ -34,4 +35,27 @@ pre {
3435
font-size: 18px;
3536
}
3637
}
38+
39+
// copy code to clipboard
40+
.copy {
41+
color: $white;
42+
position: absolute;
43+
right: 1.2rem;
44+
top: 1.2rem;
45+
opacity: 0;
46+
47+
&:active,
48+
&:focus,
49+
&:hover {
50+
background: rgba(0, 0, 0, 0.7);
51+
opacity: 1;
52+
}
53+
}
54+
55+
&:active .copy,
56+
&:focus .copy,
57+
&:hover .copy {
58+
background: rgba(0, 0, 0, 0.7);
59+
opacity: 1;
60+
}
3761
}

0 commit comments

Comments
 (0)