xiel / embla-carousel-wheel-gestures

wheel interactions for Embla Carousel
https://embla-carousel-wheel-gestures.xiel.dev/react.html
MIT License
57 stars 9 forks source link

Add option to use both scroll axes #183

Open dash-james opened 1 year ago

dash-james commented 1 year ago

Hi there,

Appreciate the work you've put into this plugin, thank you!

I was wondering if there was a way to be able to include an option to use both axes to scroll?

Thank you! James

dash-james commented 1 year ago

I wrote something similar to the Drag Handler that works quite well for the wheel events. It has support for both axes as well. Maybe there is a way we can integrate the same technique?

// Wheel Events
const handleWheel = useCallback((e) => {
    if (!embla) return
    e.preventDefault()
    // Calculate the scroll direction based on the wheel event
    const delta = e.deltaY || e.deltaX || e.wheelDelta
    const direction = delta > 0 ? -1 : 1
    // Use Embla's ScrollBody to control speed and mass
    const engine = embla.internalEngine()
    const scrollBody = engine.scrollBody
    // Calculate the rawForce (similar to DragHandler's logic)
    const rawForce = Math.abs(delta)
    // Adjust the dragFree value as needed (true for smooth scrolling, false for snapping)
    const dragFree = true // Adjust as needed
    // Use scrollTo.distance to initiate the scroll based on the calculated force
    scrollBody.useSpeed(16) // Set your desired base speed
    scrollBody.useMass(1) // Set your desired base mass
    engine.scrollTo.distance(direction * rawForce, !dragFree)
}, [embla])

useEffect(() => {
    if (!embla || !wheel) return
    if (ref.current) ref.current.addEventListener('wheel', handleWheel)
    return () => ref.current?.removeEventListener('wheel', handleWheel)
}, [embla, ref])
davidjerleke commented 1 year ago

Thanks @dash-james,

Will try it out when I get the chance!

Best, David