Skip to main content

Action

Template

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>

Example

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>