0

I want to scroll a div container to center of its scrollable area when a certain event occurs. I am using scrollIntoView to achieve this:

const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });

However, this is causing the entire page to scroll up as well. This seems to be a bug in Chrome as highlighted by this post. However, I am trying to negate its effect by scrolling the page to top every time it scrolls.

const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
window.scrollTo(0, 0);

But this doesn't work as the container doesn't scroll at all. I believe this is because I am immediately trying to scroll up the entire page after calling scrollIntoView. I want to scroll the page after the scrollIntoView animation completes. Is there a way to achieve this?

darKnight
  • 5,651
  • 13
  • 47
  • 87

1 Answers1

0

Try wrapping it so that it executes on the next turn of the event loop:

setTimeout(()=>
  window.scrollTo(0, 0);
, 0);