Function leptos_use::use_scroll

source ·
pub fn use_scroll<El, T>(
    element: El
) -> UseScrollReturn<impl Fn(f64) + Clone, impl Fn(f64) + Clone, impl Fn() + Clone>
where El: Clone + Into<ElementMaybeSignal<T, Element>>, T: Into<Element> + Clone + 'static,
Expand description

Reactive scroll position and state.

§Demo

Link to Demo

§Usage

let element = create_node_ref::<Div>();

let UseScrollReturn {
    x, y, set_x, set_y, is_scrolling, arrived_state, directions, ..
} = use_scroll(element);

view! {
    <div node_ref=element>"..."</div>
}

§With Offsets

You can provide offsets when you use use_scroll_with_options. These offsets are thresholds in pixels when a side is considered to have arrived. This is reflected in the return field arrived_state.

let UseScrollReturn {
    x,
    y,
    set_x,
    set_y,
    is_scrolling,
    arrived_state,
    directions,
    ..
} = use_scroll_with_options(
    element,
    UseScrollOptions::default().offset(ScrollOffset {
        top: 30.0,
        bottom: 30.0,
        right: 30.0,
        left: 30.0,
    }),
);

§Setting Scroll Position

Set the x and y values to make the element scroll to that position.

let element = create_node_ref::<Div>();

let UseScrollReturn {
    x, y, set_x, set_y, ..
} = use_scroll(element);

view! {
    <div node_ref=element>"..."</div>
    <button on:click=move |_| set_x(x.get_untracked() + 10.0)>"Scroll right 10px"</button>
    <button on:click=move |_| set_y(y.get_untracked() + 10.0)>"Scroll down 10px"</button>
}

§Smooth Scrolling

Set behavior: smooth to enable smooth scrolling. The behavior option defaults to auto, which means no smooth scrolling. See the behavior option on Element.scrollTo for more information.

let UseScrollReturn {
    x, y, set_x, set_y, ..
} = use_scroll_with_options(
    element,
    UseScrollOptions::default().behavior(ScrollBehavior::Smooth),
);

or as a Signal:

let (smooth, set_smooth) = create_signal(false);

let behavior = Signal::derive(move || {
    if smooth.get() { ScrollBehavior::Smooth } else { ScrollBehavior::Auto }
});

let UseScrollReturn {
    x, y, set_x, set_y, ..
} = use_scroll_with_options(
    element,
    UseScrollOptions::default().behavior(behavior),
);

§Server-Side Rendering

On the server this returns signals that don’t change and setters that are noops.