I am creating my first LiveView application and it involves a chatroom. Is there a way to set the scroll position when an event is submitted?
Right now I have a very primitive method of scrolling to the bottom of the chat messages, but I want the messages to simulate slack where the newest message appears at the bottom of the div. Using this anchor method is very slow (I can send 5-6 messages before it scrolls to the bottom) so I was wondering if there was a way I could auto scroll to the bottom when a new message is sent. Another issue I have noticed with using an anchor is if I were to scroll through the history it would auto scroll to the bottom after a couple seconds, making it impossible to read the history.
This is an application I am making to get back in to Phoenix and learn about LiveView so any help is appreciated.
I would use a client hook on the container of chat messages. Set a scroll event on mounted, that sets a flag if user scrolls to the end of messages. In updated, check the flag, if yes, scroll to the bottom (which means user was already at the bottom of messages, probably waiting for new ones), if no then do not scroll.
I do have the same kind of problem, but I’ve not yet implemented it. This is the logic I’m gonna use, so it may have flaws or implementation details. I’ll be happy if you share the end result!
Here’s my phx-hook where it will only scroll to the bottom on mount and only if you’re within a certain distance of the bottom. This allows users to scroll up to read previous messages and not have it auto scroll to the bottom if a new message comes in.