Skip to content

Instantly share code, notes, and snippets.

@magks
Created February 22, 2024 12:41
Show Gist options
  • Save magks/393d5d5be9f92aa16b28298c6c6a80ed to your computer and use it in GitHub Desktop.
Save magks/393d5d5be9f92aa16b28298c6c6a80ed to your computer and use it in GitHub Desktop.
Auto Scroll Upward or Downward Through HTML list items children of some element (E.g. Discord web app DM chat)
const ScrollDirection = {
UP: 'UP',
DOWN: 'DOWN'
};
function scrollListItems(elementSelector, scrollDirection) {
let parentElement = document.querySelector(elementSelector);
if (parentElement) {
let listItems = parentElement.querySelectorAll('li');
if (listItems.length === 0) {
console.log('No list items found.');
return;
}
// Jump to end of list
const itemToScroll = scrollDirection === ScrollDirection.UP ? listItems[0] : listItems[listItems.length - 1];
itemToScroll.scrollIntoView({ behavior: 'smooth', block: 'start' });
} else {
console.log('parent element not found.');
}
}
scrollChatUp = () => scrollListItems('main[class^=chatContent]', ScrollDirection.UP);
scrollChatDown = () => scrollListItems('main[class^=chatContent]', ScrollDirection.DOWN);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment