Skip to content

Instantly share code, notes, and snippets.

@whisher
Created May 4, 2022 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whisher/c1a9c24be9c30643acb0df7fd9755032 to your computer and use it in GitHub Desktop.
Save whisher/c1a9c24be9c30643acb0df7fd9755032 to your computer and use it in GitHub Desktop.
A svelte action for a clickable acrd
import { goto } from '$app/navigation';
/* eslint-disable */
export function linkedArticle(
node: HTMLElement,
parameters: { url: string } | undefined
): {
destroy: () => void;
} {
const a = node.querySelector('a');
let pathname = '';
if (a && !parameters) {
const url = new URL(a.href);
pathname = url.pathname;
} else if (parameters) {
pathname = parameters.url;
}
function handleClick(event: MouseEvent) {
event.preventDefault();
if (window) {
const selObj = window.getSelection();
if (selObj) {
const noTextSelected = selObj.toString();
if (!noTextSelected && pathname) {
goto(pathname);
}
}
}
}
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', handleClick);
}
};
}
/* eslint-enable */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment