htmx interview question · Most asked
How can the server trigger client-side events, and why is that useful?
Summary
With the HX-Trigger response header: a single event name, a comma-separated list, or JSON with details ({"showMessage": "Saved"}). The event fires on the triggering element and bubbles, so other elements listen with hx-trigger="myEvent from:body" and refresh themselves.
Longer Answer
It decouples components: an 'add task' endpoint doesn't need to know about every counter, badge and list that should update. htmx 2 also supports HX-Trigger-After-Swap and HX-Trigger-After-Settle (removed in htmx 4). Use lower-case, dash-separated event names if you listen with hx-on, because attribute names are lower-cased.
Key Points
- HX-Trigger response header.
- Name list or JSON with details.
- Listen with from:body.
- Decouples parts of the page.
Deep dive: htmx: Build Interactive Web Apps with HTML: Adding Contacts and Updating Several Places
More most-asked htmx questions
- How do you handle form validation errors with htmx?
- How does htmx compare with React or Vue?
- What is htmx?
- What do hx-get, hx-post, hx-put, hx-patch and hx-delete do, and how are values sent?
- What is hx-target, and what relative selectors does it support?
- What swap styles does hx-swap support?
- How does hx-trigger work? Give examples of modifiers and special triggers.
- What security risks are specific to htmx, and how do you mitigate them?