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
Click outside event? #3012
Comments
If I recall, in Svelte 2 there was one (was something like off:xyz={} The docs for Svelte 3 are less user-friendly, and if this feature exists, it's not mentioned in them. |
Okay, thank you for the answer. |
Sadly the old docs (which were at http://svelte.technology) are no longer available as that address now points to the new stuff. I'm going to grab 'em using the wayback machine (<--cannot believe that I've just written this in the age of ubiquitous version control!!) |
The old docs are available at https://v2.svelte.dev/ There is not and never was an event for clicking outside of a given element. Svelte's element events use actual DOM events, and there isn't one for clicking outside an element. You would typically attach an event handler to the entire window and check whether the target is contained within the element in question. |
Okay, thank you for all the answers! |
Haven't tried it yet but for future reference there's |
I prefer this implementation which uses a Svelte action ( https://github.com/rster2002/svelte-outside-click There is also this REPL example: https://svelte.dev/repl/0ace7a508bd843b798ae599940a91783?version=3.16.7 (I can't find the original author). |
Hi |
Here is the TS version, I hope they make Svelte REPL support TS in the future! export function clickOutside(node: HTMLElement, ignore?: string) {
const handleClick = (event: Event) => {
const target = event.target as HTMLElement;
if (!event.target || ignore && target.closest(ignore)) {
return;
}
if (node && !node.contains(target) && !event.defaultPrevented) {
node.dispatchEvent(
new CustomEvent('click_outside')
);
}
}
document.addEventListener('click', handleClick, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
}; I also made a little secondary option in case you want to ignore a certain element that is outside. This came in handle for me when I clicked the same button twice. use:clickOutside={'#user-menu-button'}
on:click_outside={profileDropdown.close} J |
For others coming to this thread, especially typescript users, i abstracted this with a svelte action into @svelte-put/clickoutside. Hope that helps. |
I am working with custom components and was using the solution provided by @jdgamble555 . while using the
with
this works with clicks from within the element and from outside. are there any issues with this solution? |
Hi,
Is there a click outside event available?
The text was updated successfully, but these errors were encountered: