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

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We saw that htmxwas fantastic for adding "Active Search". That is search as you type.
0:07 Of course we didn't want every single keystroke to drive a search. You want to let people type just a little bit and then basically the soon as
0:14 they stop and are ready to, it's Okay, that's what I'm searching for. Boom! The results pop right in. So they type here,
0:21 the results dynamically reappear here without reloading the page, but we went farther. Remember we did a couple of things,
0:28 we actually added the search text to the URL, so that would show up in the browser history, adding back and
0:35 forth support, you know, navigate back as well as very importantly we supported deep linking. So if you were to bookmark that or share that URL, that
0:45 is now possible. It'll actually regenerate exactly the same view or really rerun the same search. Maybe the data has changed.
0:52 Let's see how we did that. It really only took four hx attributes. We have hx-get /videos/search and then the trigger this time was an interesting
1:03 combination. It was keyup so when people are typing basically release the key but also changed, the text has to change in the input.
1:12 It can't be enough that it's an arrow key, key up and down. It has to be that there is a key up and the resulting value of the
1:18 input is different, and then avoiding every single keystroke hammering on the server.
1:23 We have a delay of 250 milliseconds. If you pause that long or longer that search will be sent off to the server.
1:30 We have a target that was that bottom red block where the search results went. It's just a CSS selector and
1:36 id=#search-results here, and then we want to have the history. So basically the browser history side but not the deep linking side. We said hx-push-url
1:47 is true. One of the things we did in part of this input here also to support deep linking was too pre-populate the input value with search text.
1:57 So we did this Jinja string, search_text or empty string. So when you load it up the first time it's
2:03 empty., but if you deep link to it, it's gonna say grab the search text out of the URL and then pass it back and populate this part of the page
2:12 with that text as well. Incredible, right? This is all it takes.

Talk Python's Mastodon Michael Kennedy's Mastodon