Very recently I developed a basic chat function in an application. Users could
enter and send message to each other. And the messages were shown in a list that
automatically scrolled down when a new message was received.
The problem
Let says you have a list of messages that looks like this in HTML:
HTML
This is simple list were the height is limited. If there are many messages,
there will be a scrollbar. When new messages are added you want to scroll the
list to the bottom. Unless the scrollbar is not on the bottom - then we do not
want to move it because the user have scrolled up to read earlier messages.
The solution
There are some interesting problems here. But the most important for me was to
make the code reusable. It should work on any page, even if it has several
message lists.
My solution was to run JavaScript code when every page is loaded, and let it
monitor changes to the DOM. When it detects elements that has the class
attribute auto-scroll-to-bottom, it will add an event listener that then is
submitting the form. It will also remove the event listeners if the attribute is
removed.
So, my sample code just needs to change to this:
HTML
No JavaScript is mixed in the HTML which make is nice and simple.
Anyway, the code that do this is this TypeScript code:
TypeScript
And this is how it looks in JavaScript:
JavaScript
I think this should work in all modern browsers.
Summary
I like this pattern a lot. You only need to make sure it has run once after the
page has been loaded, and then it will take care of everything after that. The
code plays nicely with Blazor. In fact, I used this code in the project I created
for me previous post
Detect and warn multiple editors.