'Automatically scroll a div not the parent element
I have a scrollable list of items on a page. The user is able to make a PUT request and update one of the items. If the PUT request is successful I make another network request to fetch the updated list. From this list I want to immediately set the recently updated element as active.
I have the code to do all of this successfully, however the scrolling not only occurs on my list but the entire page scrolls somewhat as well.
My list looks like this:
<div className={cx(styles.body)}>
<div className={styles.squadList}>
{squadList.map((squad, index) => {
const isSelected =
squad.squadId === squadSelected.squadId
? "selected"
: null;
return (
<div
className={cx(styles.item, {
[styles["item--selected"]]: isSelected,
})}
key={index}
id={`squad-list-item-${squad.squadId}`}
>
<div className={styles.details}>
<span className={styles.title}>
{squad.squadName}
</span>
<span className={styles.members}>
{squad.memberCount} members
{renderAdminIcon(squad, isSelected)}
</span>
</div>
</div>
);
})}
</div>
</div>
After the successful put request and my refetch I run
const tgtElement = document.getElementById(
`squad-list-item-${squadSelected.squadId}`
);
tgtElement.scrollIntoView();
This works and it scrolls the desired element to the top of the list, however it also scrolls the entire page a bit as well.
Solution 1:[1]
in order to achieve that you must scroll the div to the desired element.
First get the element offsetTop and than set the div top scroll to match the element top offset.
const divToScroll = document.getElementById("divToScrollId");
const tgtElement = document.getElementById(
`squad-list-item-${squadSelected.squadId}`
);
// Here where the magic happens
divToScroll.scrollTop = tgtElement.offsetTop;
This should work as long as the div to scroll has is css position set to relative.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucas Fabre |
