Copy Sourcecode to Clipboard
In educative web pages source code is often an integrated part, as it is also here.
Providing a copy to clipboard function on code blocks was always on my list and now is part of this advent calendar.
Adding the functionality to a pre-code block can be done automatically.
Writing text to the clipboard
The core functionality is using the writeText function of the navigator.clipboard:
navigator.clipboard.writeText(text);
Copy To Clipboard Icon
A common icon can be used using the following svg code:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
<path d="M30 36 v 6 H 6 V 18 v 0 h 6 m 6-12 h 24 v 24 H 18 z"
fill="none" stroke="#000"
stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
</svg>
To show this icon when the cursor hovers the source code it can be included inline into css using the rule without using javascript events:
pre code {
position: relative;
}
pre code:hover::after {
position: absolute;
top: 0;
right: 0;
width: 32px;
height: 32px;
content: "";
background-repeat: no-repeat;
background-image: url("data:image/svg+xml;utf8,<svg ...>");
}
Click to Copy Event
This function can be used in a click event to write the inner text of the code tag to the clipboard when the copy icon in the upper right corner has been clicked:
function codeCopy(evt) {
const t = evt.target;
const box = t.getBoundingClientRect();
if ((evt.clientX > box.right - 32) && (evt.clientY < box.top + 32)) {
navigator.clipboard.writeText(t.innerText);
}
}
This function can be attached to all pre > code
elements
using the following code:
document.querySelectorAll('pre code').forEach(e => {
e.addEventListener('click', codeCopy);
});
See also
- https://developer.mozilla.org/en-US/docs/Web/API/Clipboard
- https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect