Click Outside
Description
Click outside is a custom util representing a Svelte action designed for detecting when a user clicks outside of a specific HTML element.
Integration and Usage
To use click-outside util, you need to import it into your project
import { clickOutside } from './path/to/utils/click-outside';
and add it to a HTML element you want to monitor.
<div use:clickOutside on:click:click_outside={() => handleCloseOutside()}>
<!-- Your content goes here -->
</div>
Type Definition
import type { ActionReturn } from 'svelte/action';
interface Return {
'on:click_outside': () => void;
}
ActionReturn- represents the return type of a Svelte action
- can contain functions and event handlers
ReturnInterface- defines the structure of
on:click_outsideevent handler which is dispatched by theclickOutsideaction
- defines the structure of
ClickOutside Function
export function clickOutside(
node: HTMLElement
): ActionReturn<{}, Return>
Parameters
node:HTMLElement- the DOM element it monitors for outside
clicks
- the DOM element it monitors for outside
Return Type
ActionReturn<{}, Return>{}: no specifict options are passed to the actionReturn: specifies the custom eventon:click_outsidedefined in the Return interface as part of return type
Function Logic
window.addEventListener('keydown', handleEscape, true);
document.addEventListener('click', handleClick, true);
Event listeners are added to the window and document listening for keydown and click events and triggering functions handleEscape and handleClick.
Dispatch Function
function dispatch() {
node.dispatchEvent(new CustomEvent('click_outside', node));
}
Function Dispatch is a part of function clickOutside used for dispatching a custom click_outside event.
HandleClick Function
function handleClick(event: MouseEvent) {
if (node && !node.contains(event.target as HTMLElement) && !event.defaultPrevented) {
dispatch();
}
}
Function HandleClick is a part of function clickOutside that triggers the dispatch function if the click is outside of the target node.
HandleEscape Function
function handleEscape(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch();
}
}
Function HandleEscape is a part of function clickOutside that checks that triggers the dispatch function if the Escape key is pressed.
Returns
return {
destroy() {
document.removeEventListener('click', handleClick, true);
window.removeEventListener('keydown', handleEscape, true);
}
};
Function clickOutside returns an object that mathes the format of Svelte's ActionReturn interface.
It contains a function:
destroy- called when the action is no longer in use
- removes event listeners that were added to detect
clicksoutside the target element and presses ofEscapekey
Events
click_outside- triggers when a
clickis detected outside the specified element or when theEscapekey is pressed
- triggers when a