Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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::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::{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

Make sure you follow the instructions in Server-Side Rendering.

On the server this amounts to a no-op.

Installation

cargo add leptos-use-on-click-outside

Options

OnClickOutsideOptions

Options for on_click_outside_with_options.

Every option is set with a builder method of the same name, e.g. OnClickOutsideOptions::default().ignore(...). See also the API docs.

ignore

Type: ElementsMaybeSignal<web_sys::EventTarget>

List of elementss that should not trigger the callback. Defaults to [].

capture

Type: bool

Use capturing phase for internal event listener. Defaults to true.

detect_iframes

Type: bool

Run callback if focus moves to an iframe. Defaults to false.

Source

Source • Demo • Docs