I am on the latest version of SolidJS and I am unable to detect scroll events with onscroll
. Even with the basic starter code.
import type { Component } from 'solid-js';
import logo from './logo.svg';
import styles from './App.module.css';
const App: Component = () => {
return (
<div onscroll={() => {console.log("Scroll detected")}}>
<div class={styles.App}>
<header class={styles.header}>
<img src={logo} class={styles.logo} alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
class={styles.link}
href="https://github.com/solidjs/solid"
target="_blank"
rel="noopener noreferrer"
>
Learn Solid
</a>
</header>
</div>
<div class={styles.App}>
<header class={styles.header}>
<img src={logo} class={styles.logo} alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
class={styles.link}
href="https://github.com/solidjs/solid"
target="_blank"
rel="noopener noreferrer"
>
Learn Solid
</a>
</header>
</div>
</div>
);
};
export default App;
Does <div onscroll={}></div>
not work in SolidJS?
2
Answers
I have found one solution so far. That is to use
solidjs-primitives/scroll
.Scroll event is a bit tricky because the div element you are adding the
onscroll
listener may not be scrollable at all due to how CSS style is applied. What I means is the scroll bar you see may not belong the element that you added the scroll handler. So, it is best to add the event handler to the document and check if the scroll event originates from the div element inside the handler.Take a look at the live demo below, the event target is not the div element, confirming our suspicion.
Live Demo: https://playground.solidjs.com/anonymous/6470a883-42a0-49e1-8559-ac6a301c6e57
PS: The effect you added as an answer uses the same approach I described above. I don’t know its implementation details but it appears the listener is added to the window object.