#htmx #html #frontend

Day 7: Out of Band Swaps

Welcome to Day 7. One of the biggest complaints against HTML-over-the-wire is: “What if I need to update the cart count in the header AND the product list in the main view?”

Enter Out of Band (OOB) Swaps.

The Concept

Your server response usually goes into hx-target. But your response can include extra HTML elements tagged with hx-swap-oob="true".

htmx will pull those out and swap them into the DOM wherever the matching ID exists.

Example

Request: POST /add-to-cart

Response HTML:

<div>
    <!-- Main Target Content (goes into the button or message area) -->
    Item Added!
</div>

<!-- Extra update for the header -->
<span id="cart-count" hx-swap-oob="true">
    5 items
</span>

The Setup

Client:

<header>
    Cart: <span id="cart-count">4 items</span>
</header>

<main>
    <button hx-post="/add-to-cart">Buy</button>
</main>

When the response comes back, htmx updates the button text AND hunts down #cart-count in the header and updates it too.

Challenge for Day 7

  1. You have a Table of Users.
  2. You have a “Total Users: X” badge in the page title.
  3. When you delete a user row (<tr>), update the Total Users badge too.

Solution:

Response from DELETE /users/1:

<!-- 1. Swap the row with nothing (empty) to remove it -->
<tr id="user-1"></tr> 

<!-- 2. Update the counter somewhere else -->
<div id="total-count" hx-swap-oob="true">
    Total: 42
</div>

Note: To remove the row cleanly, you might want hx-swap="delete" on the client or return empty content.

You’ve completed the first week! You now core mechanics. Week 2 starts with Transitions & Animation.