on_click_outside
Listen for clicks outside an element. Useful for modals or dropdowns.
Demo
Usage
use leptos::prelude::*;
use leptos::logging::log;
use leptos::html::Div;
use leptos_use::on_click_outside;
#[component]
fn Demo() -> impl IntoView {
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.
use leptos::prelude::*;
use leptos::logging::log;
use leptos::html::Div;
use leptos_use::{on_click_outside_with_options, OnClickOutsideOptions};
#[component]
fn Demo() -> impl IntoView {
let target = NodeRef::<Div>::new();
on_click_outside_with_options(
target,
move |event| { log!("{:?}", event); },
OnClickOutsideOptions::default().ignore(["input", "#some-id"]),
);
view! {
<div node_ref=target>"Hello World"</div>
}
}
Server-Side Rendering
On the server this amounts to a no-op.
Feature
This function is only available if the crate feature
on_click_outside
is enabled