Home > Software engineering >  Why is the parent scroll event getting triggered , when scrolling inside child,
Why is the parent scroll event getting triggered , when scrolling inside child,

Time:10-11

From what I know scroll event doesn't get bubbled to the parent and only bubbles document itself then why parent scroll event is getting fired,

import { useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const refParent = useRef(null);
  const refChild = useRef(null);
  useEffect(() => {
    function handleParent() {
      console.log("Parent");
    }
    function handleChild() {
      console.log("Child");
    }
    if (refParent && refChild) {
      refParent.current.addEventListener("mousewheel", handleParent);
      refChild.current.addEventListener("mousewheel", handleChild);
    }
    return () => {
      refParent.current.removeEventListener("mousewheel", handleParent);
      refChild.current.removeEventListener("mousewheel", handleChild);
    };
  });
  return (
    <div
      style={{ width: "400px", height: "200px", background: "red" }}
      ref={refParent}
    >
      <div
        style={{ width: "100px", height: "100px", overflow: "auto" }}
        ref={refChild}
      >
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas, dolorum
        nisi, debitis optio magnam perferendis similique delectus incidunt alias
        eum dignissimos est quis assumenda doloribus rem deserunt tempora eos
        reiciendis!Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Quas, dolorum nisi, debitis optio magnam perferendis similique delectus
        incidunt alias eum dignissimos est quis assumenda doloribus rem deserunt
        tempora eos reiciendis! Lorem ipsum dolor sit amet consectetur
        adipisicing elit. Quas, dolorum nisi, debitis optio magnam perferendis
        similique delectus incidunt alias eum dignissimos est quis assumenda
        doloribus rem deserunt tempora eos reiciendis!Lorem ipsum dolor sit amet
        consectetur adipisicing elit. Quas, dolorum nisi, debitis optio magnam
        perferendis similique delectus incidunt alias eum dignissimos est quis
        assumenda doloribus rem deserunt tempora eos reiciendis!
      </div>
    </div>
  );
}

here is the live example https://codesandbox.io/s/runtime-silence-lxi1jb?file=/src/App.js

Thanks

CodePudding user response:

It's because you are using the mousewheel event and not the scroll event. The mousewheel event will bubble and is just saying did the user issue a command to their machine to attempt a scroll. It's like onClick but for the mouse wheel.

You meant to use the scroll event which means "did this frame move scroll position".

  • Related