#htmx #html #frontend

Day 4: The Art of the Swap

Welcome to Day 4.

We know when to trigger (Day 2) and where to put it (Day 3). Now we decide how it gets put there with hx-swap.

The Default: innerHTML

If you don’t specify, htmx puts the response inside the target element.

<div id="target">
    <!-- Old content -->
</div>

Becomes:

<div id="target">
    New Content
</div>

outerHTML

Replaces the entire target element including the tag itself. Crucial for replacing rows in tables or items in lists.

<button hx-get="/clicked" hx-swap="outerHTML">
    Click Me
</button>

Server response: <span>I was clicked</span>. Result: The button is gone, replaced by the span.

Insertion Swaps

Great for infinite scrolls, chat logs, or notifications.

afterbegin / beforebegin

Prepends content (top of list).

<div id="feed" hx-get="/new-posts" hx-swap="afterbegin">
    <!-- New posts appear here -->
    <div class="post">Old 1</div>
</div>

beforeend / afterend

Appends content (bottom of list).

<button hx-get="/more" hx-target="#feed" hx-swap="beforeend">
    Load More
</button>

Challenge for Day 4

  1. Imagine a notification system.
  2. You have a list <ul id="alerts">.
  3. You have a button that checks for new alerts.
  4. New alerts should appear at the top of the list naturally.
  5. Which swap strategy do you use?

Solution:

<ul id="alerts">
    <!-- alerts go here -->
</ul>

<button 
    hx-get="/alerts/check" 
    hx-target="#alerts" 
    hx-swap="afterbegin"
>
    Check Alerts
</button>

This inserts the new <li> elements inside the <ul>, before the first child.

Tomorrow: Sending Data.