This episode is for members only

Level up with a premium membership

Join now
Already a member? Sign in to continue
Playing
09. Auto scrolling the message area

Transcript

00:00
Let's take a look at a technique that we can use for any scrollable HTML element like this overflow to, first of all, always have it in the bottom. We always want to, when we load the page, be at the bottom of the message stack. But also as new messages roll in, we always want to keep this scrolled to the bottom. At the moment, we know that when we post a message from someone else, this just hangs around down here and we have to manually scroll, which is not great.
00:28
Now, to tackle the first problem of always having this scrolled at the bottom, we can create out a element at the bottom here outside of our for each loop. And we can use Alpine to always scroll to this element. So what we can do is take the element, which is this div element, and we can use scroll into view. Because this is at the bottom of our message stack, it's always going to be scrolled to within that scrollable element.
00:59
So now when I refresh the page, there is a little bit of a flicker, but you can see that this always bumps right down to the bottom. So we'll always see the latest messages. Now, if we go ahead and write a message in here, you can see that we now need to tackle the problem of always keeping this scrolled at the very bottom. To do this, what we can use and Tailwind doesn't support this, so we're going to have to add in a custom almost inline style to this is going ahead and choosing a viewport size.
01:30
We'll just use small. So this works globally and we'll say overflow anchor and we're going to set this to auto and then on the outer container. So on this container just here, we're going to set this to overflow anchor of none. Just by doing that with these two elements, any time this content overflows, we're going to go ahead and push down to the very bottom on this div.
01:56
And just before we forget, we need to give this element some height so it can actually recognize it. And we can just set that as a one pixel height. That's all we need to get this working. OK, if we head over, give both of these a refresh, we know that they end up at the bottom.
02:12
Let's add in another message. And as you can see, this element is always scrolled to on overflow. So either way round is just going to work. And of course, whoever is in the chat room is always going to see the latest message at the bottom scrolled into view.
14 episodes1 hr 23 mins

Course overview

Join a room and start chatting! This course covers building a multi-room text chat app with Livewire using Laravel Reverb for real-time updates.

Using presence channels and client-to-client whispering, we’ll also show who’s online, and who’s currently typing.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Comments

No comments, yet. Be the first to leave a comment.