Technical Article
How to add copy to clipboard vanilla javascript and css
Easily add and adjust copy to clipboard button similar to Github
You’ll need to add the following javascript code.
<script>
const copyButtonLabel = "Copy Code";
// use a class selector if available
let blocks = document.querySelectorAll("pre");
blocks.forEach((block) => {
// only add button if browser supports Clipboard API
if (navigator.clipboard) {
let button = document.createElement("button");
button.innerText = copyButtonLabel;
block.appendChild(button);
button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});
async function copyCode(block: HTMLPreElement, button: HTMLButtonElement) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
// visual feedback that task is completed
button.innerText = "Code Copied";
setTimeout(() => {
button.innerText = copyButtonLabel;
}, 700);
}
</script>
You can customize it with css as following
<style is:global>
pre {
position: relative;
overflow: auto;
/* make space */
margin: 5px 0;
padding: 1.75rem 0 1.75rem 1rem !important;
}
pre button {
position: absolute;
top: 5px;
right: 5px;
font-size: 0.8rem;
padding-bottom: 0;
padding-top: 0;
padding-left: 7px;
padding-right: 7px;
background-color: #e1e1e1;
border-radius: 5px;
text-shadow: #c4c4c4 0 0 2px;
color: black;
}
pre button:hover {
cursor: pointer;
background-color: #bcbabb;
}
</style>
After this all pre
tags should have a copy to clipboard button available.
The HTKML structure should have a code
tag and everything within it should be copied to clipboard.
In other words:
<pre>
makes the copy button available.<code>
copy the text within it as-is, including new lines
<pre>
<code>testing</code>
</pre>