Action
Template
- js
- ts
src/lib/actions/myFunction.js
export function myFunction(node) {
// the node has been mounted in the DOM
return {
destroy() {
// the node has been removed from the DOM
}
};
}
<div use:myFunction></div>
src/lib/actions/myFunction.ts
import type { Action } from 'svelte/action';
export const myFunction: Action<HTMLElement> = (node) => {
// the node has been mounted in the DOM
return {
destroy() {
// the node has been removed from the DOM
}
};
}
<div use:myFunction></div>
Example
- js
- ts
src/lib/actions/clickOutside.js
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);
}
};
}
<div use:clickOutside on:outclick={() => (alert("outclick"))}>Action</div>
src/lib/actions/clickOutside.ts
import type { Action } from 'svelte/action';
export const clickOutside: Action<HTMLElement> = (node) => {
const handleClick = (event: Event) => {
if (!node.contains(event.target as Node)) {
node.dispatchEvent(new CustomEvent("outclick"));
}
};
document.addEventListener("click", handleClick, true);
return {
destroy() {
document.removeEventListener("click", handleClick, true);
}
};
}
<script lang="ts">
import { clickOutside } from "$lib/actions/clickOutside";
</script>
<div use:clickOutside on:outclick={() => (alert("outclick"))}>Action</div>
src/additional-svelte-jsx.d.ts
declare namespace svelte.JSX {
interface DOMAttributes<T extends EventTarget> {
onoutclick?: TouchEventHandler<T> | undefined | null;
}
}