History, errors, and enhancement
Manage focus after a swap
Keep keyboard users oriented when the element they were using is replaced or an error appears elsewhere.
8 minute lesson
HTMX preserves focus for compatible input elements that keep the same stable id across a swap. This makes replacing a validation form less disruptive:
<label for="task-title">Task</label>
<input id="task-title" name="title" value="">
Keep that ID in both the initial and error form. Use focus-scroll:true on hx-swap only when restoring focus should also bring the field back into view; the default avoids unexpected scrolling during a long request.
Some changes require an intentional move. If validation reveals an error summary, make it programmatically focusable and focus it after the swap:
<div id="form-errors" tabindex="-1" role="alert">
Fix the highlighted fields.
</div>
A small htmx:afterSwap listener can focus that element when it appears. If the swap removes the focused row, move focus to the next sensible control or the list heading.
Do not move focus for every count, status, or background update. Keyboard users need continuity, not surprise. Test create, validation failure, deletion, and history restoration using only the keyboard.
Lesson completed