* New FAQ, new renderer * Push blog stuff * Fix blog posts * Add tutorial to be rendered * Update documentation/content/blog/2023-03-09-zero-config-type-safety.md Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Update documentation/content/blog/2023-03-09-zero-config-type-safety.md Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Revamp a lot of renderer, make it (soft) compatible with sveltekit * Remove markdown types * Clean up faq +page * Document stuff * Make the options more explicity * chore(site-2): Restructure docs pt 2 (#8604) * Push * Update readme * Push * inor accessibility fix * minr stuff * Add prepare * Run prettier * Remove test script * pnpm update * Update sites/svelte.dev/src/routes/examples/[slug]/+page.svelte Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> * Update sites/svelte.dev/package.json Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> --------- Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com> --------- Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
1.5 KiB
title |
---|
The use directive |
Actions are essentially element-level lifecycle functions. They're useful for things like:
- interfacing with third-party libraries
- lazy-loaded images
- tooltips
- adding custom event handlers
In this app, we want to make the orange modal close when the user clicks outside it. It has an event handler for the outclick
event, but it isn't a native DOM event. We have to dispatch it ourselves. First, import the clickOutside
function...
import { clickOutside } from './click_outside.js';
...then use it with the element:
<div class="box" use:clickOutside on:outclick={() => (showModal = false)}>Click outside me!</div>
Open the click_outside.js
file. Like transition functions, an action function receives a node
(which is the element that the action is applied to) and some optional parameters, and returns an action object. That object can have a destroy
function, which is called when the element is unmounted.
We want to fire the outclick
event when the user clicks outside the orange box. One possible implementation looks like this:
export function clickOutside(node) {
const handleClick = (event) => {
if (!node.contains(event.target)) {
node.dispatchEvent(new CustomEvent('outclick'));
}
};
document.addEventListener('click', handleClick, true);
return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
}
Update the clickOutside
function, click the button to show the modal and then click outside it to close it.