Skip to content

Instantly share code, notes, and snippets.

@DoronovIV
Last active February 7, 2025 13:10
Show Gist options
  • Save DoronovIV/809ce5581b825eb597581c2bdd7980af to your computer and use it in GitHub Desktop.
Save DoronovIV/809ce5581b825eb597581c2bdd7980af to your computer and use it in GitHub Desktop.
Automatically set scroll for a scrollable container
/**
We've had a case that utilized auto scroll to the bottom of the scrollabe list-container
on each new element added. Some time after that we've encountered a similar task however
in that specific case the scroll should be applied exactly to the middle of a parent element.
Simply dividing the height in 2 did not work out, so ChatGPT has for once adviced a nice
thing (It only took 2 attempts to generate that idea).
*/
/** scroll to the bottom */
const bottomPosition = this.listContainer.nativeElement.clientHeight;
this.listContainer.nativeElement.scrollTo({
top: bottomPosition,
behavior: 'auto',
});
/** scroll to the middle */
const middlePosition = (this.listContainer.nativeElement.scrollHeight - this.listContainer.nativeElement.clientHeight) / 2;
this.listContainer.nativeElement.scrollTo({
top: middlePosition,
behavior: 'auto',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment