javascripthtmlcssreactjsdom

not able to scroll two elements simultaneously


in reactjs, I have a function that scrolls elements when given a useRef:

 ref.current?.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "center",
    });

When this function is called on multiple elements at once, only the one that is called first will actually scroll.

So is it just not possible to scroll multiple elements at once?

If it is possible, what am I do wrong?


Solution

  • If you use scrollIntoView, only the first one will scroll because scrollIntoView triggers the scrolling operation. A browser can only handle one scroll at one time.

    Here is a solution with window.scrollTo for your problem :

    const scrollToElements = (refs) => {
      refs.forEach((ref) => {
        const rect = ref.current.getBoundingClientRect();
        window.scrollTo({
          top: rect.top + window.scrollY,
          left: rect.left + window.scrollX,
          behavior: "smooth",
        });
      });
    };

    Hope it helps !