Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Copy to Clipboard Integration #260

Open
jottin opened this issue Feb 16, 2023 · 1 comment
Open

Copy to Clipboard Integration #260

jottin opened this issue Feb 16, 2023 · 1 comment

Comments

@jottin
Copy link

jottin commented Feb 16, 2023

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>

@jottin
Copy link
Author

jottin commented Feb 21, 2023

Not that this helps this issue, but I did run Prism and it seems to fix 'copy to clipboard'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant