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?
Try wrapping it so that it executes on the next turn of the event loop:
setTimeout(()=>
window.scrollTo(0, 0);
, 0);
You can use the parameters that are defined for scrollIntoView().
scrollIntoView documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Follow this link for solution: https://thewebdev.info/2022/04/21/how-to-fix-scrollintoview-causing-the-whole-page-to-move-with-javascript/#:~:text=move%20with%20JavaScript%3F-,To%20fix%20scrollIntoView()%20causing%20the%20whole%20page%20to%20move,block%20set%20to%20'nearest'%20.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.