HTMX + Flask: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Course conclusion and review
Lecture: Infinite scroll with htmx

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The final fun feature we added with htmx was "Infinite Scroll".
0:05 And remember we added this to the video feed where we're showing basically all the videos in the system, sorted. Now in our example,
0:13 there weren't so many videos that we couldn't actually put them on the page.
0:17 But if you have 1000 or 10,000 or a million or nearly unlimited amounts of content obviously you need to do something like this.
0:26 So the idea was when you get to the bottom of the page, that's going to trigger some sort of request to the server and as soon as that happens
0:33 we want to show an activity behavior so the user knows that it's not just empty and then something will pop in but oh look,
0:40 it's working so we have this little set of gray bars and then goes to the server,
0:44 gets some more results. I called these fragments pages because it's kind of like
0:48 pagination but based on scrolling instead of a next previous type of navigation and that's it
0:54 That was infinite scroll. And again super straightforward to do with htmx. We render the set of videos that were on that current page.
1:03 So here we have for v in videos, render_partial off it goes. And then as long as there are more pages, we're
1:09 going to add this div. Remember it could be anything, it could be an image. It could be basically any HTML element, but I chose
1:16 a div because that has no real visual representation. It's going to have an hx-get /feed/partial for the next page.
1:23 So remember we're passing your current page to this partial view, like you're on page 3. So if you get to the bottom of page 3
1:29 you need page 4 for the next set. So we carry that forward through each request and then pass it back again.
1:36 The trigger, this is the infinite scroll aspect is revealed. You scroll the bottom, it reveals this invisible piece here and off it goes.
1:45 And what we swap out is the outer HTML, completely replace it with basically recursively calling this entire template with the next set of videos.
1:55 The other thing, here in orange that you see that we had, that's the bars we didn't do anything special to make them appear.
2:01 They were just literally there at the bottom of the page. But soon as they were visible to the user, that already kicked off the going and
2:09 getting the next page from the server. If there's no more pages than we don't even show this.
2:14 So then the bars are gone. That's infinite scroll with htmx.


Talk Python's Mastodon Michael Kennedy's Mastodon