Getting scroll data from a div #3890
Replies: 1 comment
-
Here's the (possibly bad/dumb) solution I came up with, in case it helps anyone: use dioxus::prelude::use_hook_with_cleanup;
use dioxus_logger::tracing;
use snafu::{OptionExt, Snafu};
use std::{cell::RefCell, ops::Deref, rc::Rc};
use tracing::{debug, error, info, warn};
use web_sys::wasm_bindgen::JsCast;
#[derive(Snafu, Debug)]
pub enum ScrollError {
CouldNotFindElement,
CouldNotAddListener { info: Option<String> },
}
#[derive(Debug, Clone)]
pub struct ScrollData {
pub scroll_top: i32,
pub scroll_left: i32,
pub scroll_width: i32,
pub scroll_height: i32,
pub client_top: i32,
pub client_left: i32,
pub client_width: i32,
pub client_height: i32,
}
impl ScrollData {
pub fn vertical_scroll_progress(&self) -> f64 {
self.scroll_top as f64 / (self.scroll_height as f64 - self.client_height as f64)
}
pub fn horizontal_scroll_progress(&self) -> f64 {
self.scroll_left as f64 / (self.scroll_width as f64 - self.client_width as f64)
}
}
pub fn use_scroll(
target_id: impl AsRef<str>,
mut callback: impl FnMut(ScrollData) + 'static,
) -> Result<(), ScrollError> {
let target_id: &str = target_id.as_ref();
let document = gloo::utils::document();
let target_element = document
.get_element_by_id(&target_id)
.context(CouldNotFindElementSnafu)?;
let elem = target_element.clone();
let closure = web_sys::wasm_bindgen::prelude::Closure::wrap(Box::new(move || {
let data = ScrollData {
scroll_top: elem.scroll_top(),
scroll_left: elem.scroll_left(),
scroll_width: elem.scroll_width(),
scroll_height: elem.scroll_height(),
client_top: elem.client_top(),
client_left: elem.client_left(),
client_width: elem.client_width(),
client_height: elem.client_height(),
};
callback(data.clone());
}) as Box<dyn FnMut()>);
target_element
.add_event_listener_with_callback("scroll", closure.as_ref().unchecked_ref())
.map_err(|x| ScrollError::CouldNotAddListener {
info: x.as_string(),
})?;
closure.forget();
Ok(())
} Anyone who finds a better solution, I'd love to hear it! :3 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In Dioxus, what's the best/recommended way of grabbing information about the page's current scroll position? I've tried doing this in my
div
:But it can't seem to get at the interior data, if any:
Serializing to JSON, then doing the test gives me this:
rust-analyzer
doesn't suggest any member values or methods that look useful, and skimming the codebase has also revealed little, if anything.I have confirmed that JS is able to extract the data:
So I believe I'm targeting the right div (
container
).Beta Was this translation helpful? Give feedback.
All reactions