Function on_click_outside

Source
pub fn on_click_outside<El, M, F>(
    target: El,
    handler: F,
) -> impl FnOnce() + Clone + Send + Sync
where El: IntoElementMaybeSignal<EventTarget, M>, F: FnMut(Event) + Clone + 'static,
Expand description

Listen for clicks outside an element. Useful for modals or dropdowns.

§Demo

Link to Demo

§Usage

let target = NodeRef::<Div>::new();

on_click_outside(target, move |event| { log!("{:?}", event); });

view! {
    <div node_ref=target>"Hello World"</div>
    <div>"Outside element"</div>
}

This function uses Event.composedPath() which is not supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include this code snippet on your project.

§SendWrapped Return

The return value of this function is a sendwrapped function to remove all event listeners. It can only be called from the same thread that called on_click_outside.

§Excluding Elements

Use this to ignore clicks on certain elements.

on_click_outside_with_options(
    target,
    move |event| { log!("{:?}", event); },
    OnClickOutsideOptions::default().ignore(["input", "#some-id"]),
);

§Server-Side Rendering

On the server this amounts to a no-op.