Respond to onWheel
events
#486
Answered
by
inokawa
jackhodkinson
asked this question in
Q&A
-
Is there any way to distinguish between a scroll event triggered by I can see I have a situation where I want to detect when the user interacts with a mouse scroll to pause an autoscrolling feature I've implemented. |
Beta Was this translation helpful? Give feedback.
Answered by
inokawa
Aug 8, 2024
Replies: 1 comment 2 replies
-
I have a workaround that is fine for now, but would be interested to know if there is a way to do it more elegantly. import { VList, VirtualizerHandle } from 'virtua';
import { useEffect, useRef, useState } from 'react';
function App() {
const [items, setItems] = useState<string[]>(Array.from({ length: 1000 }, (_, i) => `Item ${i + 1}`));
const nextIndex = useRef<number>(0);
const scrollRef = useRef<VirtualizerHandle>(null);
const didUserScroll = useRef<boolean>(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleWheel = () => {
didUserScroll.current = true;
};
const scrollElement = containerRef.current;
scrollElement?.addEventListener('wheel', handleWheel);
return () => {
scrollElement?.removeEventListener('wheel', handleWheel);
};
}, []);
useEffect(() => {
const intervalId = setInterval(() => {
if (didUserScroll.current) return;
nextIndex.current += 1;
if (nextIndex.current < items.length) {
scrollRef.current?.scrollToIndex(nextIndex.current);
} else {
clearInterval(intervalId);
}
}, 1000);
return () => clearInterval(intervalId);
}, [items.length]);
return (
<div ref={containerRef}>
<VList ref={scrollRef} height={500}>
{items.map((item, index) => (
<div key={index}>{item}</div>
))}
</VList>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What you posted, or getting scrollable element with document.querySelector like #387 (comment) are the easiest ways I think. Or if you use Virtualizer instead of VList, you can access the scrollable element directly.
And I think it's ok to add
onWheel
to the type definition of props of VList likeonKeyDown
if it's convenient. Maybe I'll fix it later(or PR welcome).virtua/src/react/types.ts
Line 5 in 7efb6b8