Add copy content links to my code snippets
Many blogs are like this one, where they contain a few code snippets that readers might want to copy to their clipboard to re-use somewhere else.
This article describes a custom HTML gadget that will automatically add the material design icon as a copy-to-clipboard link, for any <code> tags in the content.
Note: This gadget assumes that all the code tags have a relatively-positioned container. In this blog, all the <code> tags are nested in <pre> tags, which are relatively positioned.
Happy code-snippeting!
This article describes a custom HTML gadget that will automatically add the material design icon as a copy-to-clipboard link, for any <code> tags in the content.
Note: This gadget assumes that all the code tags have a relatively-positioned container. In this blog, all the <code> tags are nested in <pre> tags, which are relatively positioned.
Material Design font
While Blogger's new templates feature a range of the material design icons, they don't offer all of them - the Material icons guide notes that you can massively reduce the size of the SVG by only using the ones you need.
The web-font does weigh in at ~56KB, but you user will benefit from it being cached by any other website they have visited that also uses the font.
<link href='https://fonts.googleapis.com/icon?family=Material+Icons'
rel='stylesheet' />
The custom HTML gadget
<script>
// Load Clipboard if we haven't already got it.
window.setTimeout(function() {
if (typeof Clipboard !== 'undefined') {
return;
}
var s = document.createElement('script');
s.src = 'https://cdn.rawgit.com/zenorocha/clipboard.js/v1.6.1/dist/clipboard.min.js';
document.querySelector('head').appendChild(s);
}, 500);
</script>
<script>
window.setTimeout(function() {
if (typeof Clipboard === 'undefined' || !Clipboard) {
return;
}
var codes = document.querySelectorAll('code');
if (!codes || codes.length < 1) return;
// Load material font.
var l = document.createElement('link');
l.rel = 'stylesheet';
l.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
document.querySelector('head').appendChild(l);
// Add copy-to-clipboard links.
codes
.forEach(c => {
var copyLink = document.createElement('div');
copyLink.setAttribute('class', 'copy');
copyLink.innerHTML = '';
copyLink.title =
_WidgetManager._GetAllData().messages.copy || 'Copy';
c.parentElement.insertBefore(copyLink, c);
var clipboard = new Clipboard(copyLink, {
text: function(trigger) {
return c.innerText;
}
});
clipboard.on('success', e => {
alert(
_WidgetManager._GetAllData().messages.copiedToClipboard
|| 'Copied to clipboard');
});
});
}, 3000);
</script>
<style>
pre .copy {
font-family: 'Material Icons';
font-size: 24px;
position: absolute;
right: 0;
margin: 8px;
cursor: pointer;
}
pre .copy:not(:hover) {
opacity: 0.4;
}
</style>
Happy code-snippeting!
Comments
Post a Comment