Triggers, forms, and feedback
Choose a custom trigger
Request on load, visibility, input, a custom event, or a timed interval when the feature genuinely requires it.
Clicks, changes, and submits cover most features. Some need a request without direct user action on the element: lazy-loaded content, a status poll, or a request started elsewhere in your code. hx-trigger handles all of these.
Load content when it scrolls into view:
<section hx-get="/recommendations" hx-trigger="revealed">
Loading recommendations…
</section>
Use load when a fragment is required right after initialization. Use revealed when scrolling the window should fetch it. For an element inside an overflow container, use intersect so Intersection Observer detects visibility correctly. The placeholder text matters. It is what people see until the trigger fires, so make it honest.
Polling uses a timing declaration:
<div hx-get="/jobs/42/status" hx-trigger="every 5s">
Processing…
</div>
The server can return status 286 to stop HTMX polling when the job reaches a terminal state. Without that stop condition, finished jobs keep generating a request every five seconds for as long as the tab stays open. I avoid polling when a user action, normal refresh, SSE extension, or WebSocket extension fits better.
The most flexible option is a custom event:
<div hx-get="/notifications"
hx-trigger="notificationsChanged from:body"></div>
Another script or an HX-Trigger response header can emit notificationsChanged. From JavaScript it is one line:
document.body.dispatchEvent(new Event('notificationsChanged'))
The from:body modifier tells HTMX to listen on the body instead of the element itself. This solves cases where no element event fits. A <select> where one option must load content is a classic example: options fire no events of their own, so a change handler dispatches a custom event and the HTMX element reacts.
When a custom trigger seems dead, check the wiring first. The event must fire on the same element named in from:. Test by dispatching the event from the DevTools console and watching the Network panel for the request.
Lesson completed