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

Is there a copy button? #63

Open
jeffski opened this issue Nov 30, 2021 · 1 comment
Open

Is there a copy button? #63

jeffski opened this issue Nov 30, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@jeffski
Copy link

jeffski commented Nov 30, 2021

Not an issue, but I was wondering if there are any code examples or plugins that would add a copy button/icon to the code block so you can copy it to the clipboard?

@zachleat zachleat added the enhancement New feature or request label Jun 28, 2022
@christopherpickering
Copy link

I made a pretty simple way to do it using some javascript and tailwindcss -

in the .eleventy.js I add a few classes to the pre:

eleventyConfig.addPlugin(syntaxHighlight, {
    preAttributes: {
      class: ({ language }) => `group/code animate-fade rounded-lg bg-slate-900/80 language-${language || 'plain'}`,
    },
  });

Then I have a copy_code.js file I include in all my pages:

(() => {
  const code = document.querySelectorAll('pre[class*="language"]');

  const buttonClasses = [
    'absolute',
    'right-4',
    'top-4',
    'border',
    'rounded-md',
    'p-2',
    'bg-white/80',
    'hover:bg-white',
    'text-slate-800',
    'hover:text-slate-900',
    'opacity-0',
    'group-hover/code:opacity-100',
    'transition-opacity',
    'transition-colors',
  ];

  code.forEach((pre) => {
    pre.classList.add('relative');

    const button = document.createElement('button');
    button.classList.add(...buttonClasses);
    button.innerHTML =
      '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>';

    button.addEventListener('click', () => {
      navigator.clipboard.writeText(pre.textContent);
    });
    pre.appendChild(button);
  });
})();

Now when I hover over the code block I get a nice button:

image

Ps, I'm using eleventy-plugin-rollup, you might need to tweak the js to run properly in your browser.

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

No branches or pull requests

3 participants