Using hx-on on a list partial (htmx Active Search)
#3852
-
|
Hello, can you use I have this code on the front-end; when I type in a search query, the function I want So I thought |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Yes, First, use the kebab-case htmx event name in attributes. Attribute names are lower-cased by the DOM, so <input
type="search"
id="exercisesSearch"
class="search"
name="q"
placeholder="Type to search exercises..."
required
hx-post="/exercises/search"
hx-trigger="input changed delay:200ms, search"
hx-target="#resultsContainer"
hx-on::after-swap="handleLoad()"
/>Second, for your use case I would usually attach this once globally and check the swap target: <script>
function handleLoad() {
console.log("Partial content has been loaded!");
// initialize keyboard navigation here
}
document.body.addEventListener("htmx:afterSwap", function (event) {
if (event.detail.target.id === "resultsContainer") {
handleLoad();
}
});
</script>So: |
Beta Was this translation helpful? Give feedback.
Yes,
hx-oncan be used there, but there are two gotchas in your example.First, use the kebab-case htmx event name in attributes. Attribute names are lower-cased by the DOM, so
afterRequestis not the safe form. Useafter-request, or the htmx shorthand:Second, for your use case
after-requestis probably the wrong lifecycle event. It only tells you the request finished. Since you want to initialize keyboard navigati…