Skip to content

Copy to Clipboard Integration #260

Description

@jottin

Like this highlighter a lot. I tried integrating a copy to clipboard button on each code snippet with highlighting. The copy function only works if I remove Rainbow from the page. Any advice is welcomed. Here is the script I wrote that adds a button and copies to the clipboard...

`const copyButtonLabel = "Copy";
// use a class selector if available
let blocks = document.querySelectorAll("pre.lang-html");
blocks.forEach((block) => {
// only add button if browser supports Clipboard API
if (navigator.clipboard) {
let button = document.createElement("button");
$(button).addClass( "btn btn-secondary2" );
button.innerText = copyButtonLabel;
block.appendChild(button);
button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});

async function copyCode(block, button) {
let code = block.querySelector("code");
let text = code.innerText;
await navigator.clipboard.writeText(text);
// visual feedback that task is completed
button.innerText = "Copied";
setTimeout(() => {
button.innerText = copyButtonLabel;
}, 700);
}`

<pre class="lang-html" tabindex="0"><code data-language="html"> &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col"&gt;Column 1&lt;/div&gt; &lt;div class="col"&gt;Column 2&lt;/div&gt; &lt;div class="col"&gt;Column 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions