How to make the carousel scroll only when the cursor is on it, istead of anywhere on the windows?

1.5k Views Asked by At

I am using react-elastic-carousel in my app to scroll vertically between four components and each of them has some infos to show when scrolling on them. What I want to do is that the scrolling functionality should be happend only when the cursor is on the carousel and not everywhere on the page like is currently happening now. how I can make it possible any advices? Thanks a lot.

Here is what I did so far:

codesandbox.io/s/compassionate-leftpad-zzueys?file=/src/App.js

News.js:

    import React, {useEffect, useRef } from "react";
    import Carousel from "react-elastic-carousel";
    import "./ news.css";
    import {
      Center,
      Areas,
      Place,
      Others,
    } from "./Contents";
    
    const News = () => {
    
      useEffect(() => {
        document.title = "News";
      });
    
      const prevItemObject = "prev";
      const nextItemObject = "next";
    
      const slider = useRef(null);
    
      function scroll(e) {
        if (slider === null) return 0;
    
        e.wheelDelta > 0
          ? slider.current.onNextStart(prevItemObject, nextItemObject)
          : slider.current.onPrevStart();
      }
    
      useEffect(() => {
        window.addEventListener("wheel", scroll, true);
    
        return () => {
          window.removeEventListener("wheel", scroll, false);
        };
      }, []);
    
      return (
        <div className="container">
          <Carousel
            onScroll={scroll}
            verticalMode
            itemsToShow={1}
            enableSwipe={true}
            ref={slider}
          >
            <Relevant />
            <SearchByAreas />
            <FindAPlaceToLive />
            <FindTheRightRoomie />
          </Carousel>
        </div>
      );
    };
    
    export default News;

App.js:

import React from "react";
import News from "./News";

const App = () => {
  return (
    <div>
      <News />
    </div>
  );
};
export default App;
1

There are 1 best solutions below

14
On

your wheel event listener is on window for now, it will listen all the wheel events on the window. Maybe you could add the listener on the slider ref like this :

slider.current.addEventListener("wheel", scroll, true);

Could you provide a codepen sample please ? It would be easier to test it ;)