Hexo Copy Button For Code Block

Add Copy Button For Hexo Code Block

I am using Clipboard.js to achieve this.

Step 1:

Create a clipboard-use.js file in your JavaScript folder. In my case, the path is:
/var/www/myblog/themes/landscape/source/js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
!function (window, document) {
var initCopyCode = function() {
var copyHtml = '';
copyHtml += '<button class="btn-copy" data-clipboard-snippet>';
copyHtml += ' <i class="fa fa-copy"></i><span>Copy</span>';
copyHtml += '</button>';
$(".highlight .code pre").before(copyHtml);
new ClipboardJS('.btn-copy', {
target: function(trigger) {
return trigger.nextElementSibling;
}
});
};
initCopyCode();
}(window, document);

Step 2:

Add the script tag to the after-footer template. Make sure to place it below the jQuery script tag.
In my case, the file is located at:
/var/www/myblog/themes/landscape/layout/_partial/after-footer.ejs

1
2
3
4
<!-- Load Clipboard.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/clipboard.min.js"></script>
<!-- Load your custom script -->
<script type="text/javascript" src="/js/clipboard-use.js"></script>

Step 3:

Add the necessary CSS.
For this demo, I have added the styles in: /var/www/myblog/themes/landscape/source/css/style.styl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//copy button in code block

.highlight{
position: relative;
}
.btn-copy {
display: inline-block;
cursor: pointer;
background-color: #eee;
background-image: linear-gradient(#fcfcfc,#eee);
border: 1px solid #d5d5d5;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-appearance: none;
font-size: 13px;
font-weight: 700;
line-height: 20px;
color: #333;
-webkit-transition: opacity .3s ease-in-out;
-o-transition: opacity .3s ease-in-out;
transition: opacity .3s ease-in-out;
padding: 2px 6px;
position: absolute;
right: 5px;
top: 5px;
opacity: 0;
}
.highlight:hover .btn-copy{
opacity: 1;
}
.btn-copy span {
margin-left: 5px;
}

Step 4:

Run the following commands in your terminal:

1
2
3
cd /var/www/myblog/
hexo clean && hexo g
hexo server

Done 🎉

Your Hexo blog should now display a Copy button in the code blocks, allowing users to quickly copy the code. 🚀