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

action: copy to clipboard on click #17

Open
kindoflew opened this issue Feb 5, 2021 · 2 comments
Open

action: copy to clipboard on click #17

kindoflew opened this issue Feb 5, 2021 · 2 comments

Comments

@kindoflew
Copy link

Copies text to clipboard when clicked. Attach to the node you want to copy or, with the optional target parameter, attach to a button to copy the desired text. I've seen this used a lot for coding tutorials, specifically for copying long terminal commands.

<p use:clickToCopy> Click to copy this text </p>

or

<button use:clickToCopy={'p'}> Click to copy that text </button>

...

export function clickToCopy(node, target) {
  async function copyText(event) {
    const text = target 
      ? document.querySelector(target).innerText 
      : event.target.innerText;

    try {
      await navigator.clipboard.writeText(text);
    } catch(e) {
    // not sure what kind of error handling.
    // could have try/catch dispatch
    // success/failure events so the dev
    // can use it to alert users of the outcome?
    }
  }

  node.addEventListener('click', copyText);
	
  return {
    destroy() {
      node.removeEventListener('click', copyText);
    }
  }
}

REPL example: https://svelte.dev/repl/667d8ac94e2349f3a1b7b8c5fa4c0082?version=3.32.1

Would be happy to try a PR if people like this.

@swyxio
Copy link
Owner

swyxio commented Jan 19, 2022

sorry for the delayed response - interesting idea! not sure about the a11y angle of offering it for a button or a p tag. but i like it that its not trivial to implement so it could be helpful in a library.

leaving it open for people to find.

@kindoflew
Copy link
Author

kindoflew commented Feb 4, 2022

no worries! it gave me time to actually learn how to use jsdom properly 😂

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

2 participants