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

add action clickToCopy #21

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/clickToCopy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Action } from "./types";

/**
*
* Copies the text of an element on click: either of the element
* it's attached to or a different element using the target
* parameter. Target is a string representing a valid CSS selector.
*
* Usage:
* <p use:clickToCopy> ... </p>
*
* or
*
* <button use:clickToCopy={'p'}> ... </button>
*
* Demo: https://svelte.dev/repl/667d8ac94e2349f3a1b7b8c5fa4c0082?version=3.32.1
*
*/

export function clickToCopy(node: HTMLElement, target?: string): ReturnType<Action> {
async function copyText() {
let text: string = target
? (document.querySelector(target) as HTMLElement).innerText
: node.innerText;

try {
await navigator.clipboard.writeText(text);

node.dispatchEvent(
new CustomEvent("copysuccess", {
bubbles: true,
})
);
} catch (error) {
node.dispatchEvent(
new CustomEvent("copyerror", {
bubbles: true,
detail: error,
})
);
}
}

node.addEventListener("click", copyText);

return {
destroy() {
node.removeEventListener("click", copyText);
},
};
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './pannable';
export * from './lazyload';
export * from './preventTabClose';
export * from './shortcut';
export * from './clickToCopy';