skip to Main Content

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?

2

Answers


  1. You’re right. when you use scrollIntoView on multiple elements, only the last scroll might show up because the browser handles one scroll at a time. To fix this, just add a small delay between each scroll.

    Login or Signup to reply.
  2. When you try to trigger multiple scrolls at once using scrollIntoView, only the first scroll typically completes because the subsequent scroll commands might be ignored.

    Try with window.scrollTo or element.scrollTo for manual control,
    Instead of relying on scrollIntoView, you can manually control the scroll of each element using scrollTo or scrollBy with a smooth behavior.

        const scrollElements = () => {
      if (ref1.current && ref2.current) {
        ref1.current.scrollTo({ top: 0, behavior: 'smooth' });
        ref2.current.scrollTo({ top: 0, behavior: 'smooth' });
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search