htmx on Sinatra

—interactive web pages with hypermedia

Part 8: Swapping Out the Parent Element

Right now, our "thank you" message gets insterted into the DOM right where the button used to be. This is OK — but wouldn't it be better, in terms of user experience, to replace the entire opt-in element? Our "Join waiting list" call-to-action still hangs around above the "thank-you" message, and it doesn't look quite right.

Remember that we can target elements by id? We make the following changes:

<div id="opt-in" class="focus">

<button type="submit" hx-swap="#opt-in">

Let's submit the form, and see what happens. It looks like nothing has changed! The "thank-you" message is still inserted below the form element. We must go back to inspecting our HTML!

An htmx-based workflow is very HTML-centric. When something doesn't work as intended, we proceed by comparing the structure of our HTML document to what we had expected. We never lose sight of the fact that our stack's ultimate purpose is to render HTML to the browser. So instead of designing layers of abstractions for doing that (likely badly), our workflow is anchored in editing HTML directly (or rather, its extended form), using our editor and the browser with its rich set of tools.

In our current markup, the element we want swapped with the server response sits outside the element that's issuing the hx-post="/" — which is the form element.

Could it be that the form element cannot swap in a subtree that's higher up in the DOM tree?

We move the opt-in element with its children inside the form — and hey!

Our form submission now works just as intended.