Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 28 ยท Practice and Review

Exercises with Solutions

Twelve graded HTMX and Alpine.js exercises with runnable starters, hidden solutions and broken snippets to debug. Practice what you learned, then check your work.

Reading about x-data and hx-get is one thing. Typing them from a blank page is another. This lesson gives you twelve exercises, graded from easy to hard, across both libraries. Six come with a runnable starter you can edit right here; the rest ask you to write or fix code in your own editor or in any TryIt from this track.

Each solution is hidden. Try the exercise first, run it, and only then open the solution to compare. Your answer does not have to match mine character for character. If it behaves the same, it is correct.

How to practice

Try first Spend at least five minutes before peeking.
Run it Check the behavior, not just the syntax.
Compare Open the solution and note the differences.
Repeat later Redo the hard ones a week from now.
1 / 2

Part 1: Alpine.js

You need reactive state, bindings and lists for these.

Exercise 1: A counter with limits

Build a counter with a minus button, a plus button and the number between them. The counter must never go below 0 or above 5, and each button must be disabled when its limit is reached.

Exercise 1 starter
Show solution
HTML
<div x-data="{ count: 0 }">
  <button @click="count--" :disabled="count <= 0">-</button>
  <span x-text="count"></span>
  <button @click="count++" :disabled="count >= 5">+</button>
</div>

:disabled takes an expression, so the button turns off by itself whenever the condition is true. Disabling is more robust than checking the limit inside the click handler, because the user also sees why nothing happens.

Exercise 2: A password checker

Show a text input and, under it, a message that reads "Too short" in red while the password has fewer than 8 characters and "Looks good" in green from 8 characters on. Use x-model and a :class binding.

Exercise 2 starter
Show solution
HTML
<div x-data="{ password: '' }">
  <input type="text" placeholder="Type a password" x-model="password">
  <p :class="password.length >= 8 ? 'ok' : 'bad'"
     x-text="password.length >= 8 ? 'Looks good' : 'Too short'"></p>
</div>

A tidier version moves the condition into a getter: get strong() { return this.password.length >= 8 }, then uses strong in both places.

Exercise 3: A filterable list

Given the array ['Apple', 'Apricot', 'Banana', 'Blueberry', 'Cherry'], show it as a list and add a text input that filters it as you type, ignoring letter case. Show "No matches" when the filter removes everything.

Show solution
HTML
<div x-data="{
  q: '',
  fruit: ['Apple', 'Apricot', 'Banana', 'Blueberry', 'Cherry'],
  get shown() {
    return this.fruit.filter(f => f.toLowerCase().includes(this.q.toLowerCase()))
  }
}">
  <input x-model="q" placeholder="Filter">
  <ul>
    <template x-for="f in shown" :key="f">
      <li x-text="f"></li>
    </template>
  </ul>
  <p x-show="shown.length === 0">No matches</p>
</div>

The getter keeps the original array intact and returns a new filtered one. x-for must live on a <template> tag and that template must have one root element.

Exercise 4: Close a menu by clicking outside

Create a button that toggles a small menu box. Clicking anywhere outside the menu must close it, and pressing Escape must close it too.

Exercise 4 starter
Show solution
HTML
<div x-data="{ open: false }"
     @click.outside="open = false"
     @keydown.escape.window="open = false">
  <button @click="open = !open">Menu</button>
  <div class="menu" x-show="open">
    Profile<br>Settings<br>Sign out
  </div>
</div>

.outside fires when a click lands anywhere except inside that element, and .window listens for the key on the whole page. The .outside listener sits on the wrapper, so the toggle button counts as inside; if you put it on the menu box instead, a click on the button would be "outside" and fight with the toggle. Also note the menu is not shown until the wrapper's state changes, so the page needs no x-cloak unless you see a flash. See Events, Modifiers and Refs.

Part 2: HTMX

For these you need the mock server stub and the lessons on requests, targets and swaps and forms.

Exercise 5: Load a greeting

A button labeled "Greet me" should fetch /greeting and show the returned HTML inside the box under it, replacing the box's content. The server route returns <strong>Hello from the server!</strong>.

Exercise 5 starter
Show solution
HTML
<button hx-get="/greeting" hx-target="#box">Greet me</button>
<div id="box">Nothing yet.</div>

The default swap is innerHTML, so the box's old text is replaced and the box itself stays. Without hx-target, the response would replace the content of the button.

Exercise 6: Add to a list at the end

A form with one input named item posts to /items. The server returns one <li> with the item text. Make each new <li> appear at the end of the <ul id="list">, without replacing the existing items.

Show solution
HTML
<form hx-post="/items" hx-target="#list" hx-swap="beforeend">
  <input name="item" required>
  <button>Add</button>
</form>
<ul id="list"></ul>
JavaScript
server("POST", "/items", ({ form }) => "<li>" + escapeHtml(form.item) + "</li>");

beforeend inserts the response as the last child of the target. A real server must escape the text it echoes back; see Server-Side Setup. Add hx-on::after-request="this.reset()" to the form if you also want the input emptied after each add.

Exercise 7: Live search with a delay

An input should call /search?q=... while the user types, but only after they pause for 300 ms, and only when the text actually changed. Results go into #results.

Exercise 7 starter
Show solution
HTML
<input name="q" placeholder="Search a language"
       hx-get="/search"
       hx-trigger="input changed delay:300ms"
       hx-target="#results">

input is the event, changed skips requests when the value is the same as the last time, and delay:300ms restarts a timer on every keystroke. An input element sends its own name=value pair automatically on a GET. See Verbs, Triggers and Parameters.

Exercise 8: Delete a row with confirmation

Each row of a table has a Delete button. Pressing it must ask "Delete this row?", and if the user agrees, send DELETE /rows/ID and remove the whole row from the page when the server answers with an empty body.

Show solution
HTML
<tr id="row-7">
  <td>Invoice 7</td>
  <td>
    <button hx-delete="/rows/7"
            hx-confirm="Delete this row?"
            hx-target="closest tr"
            hx-swap="outerHTML">Delete</button>
  </td>
</tr>

closest tr finds the nearest ancestor row, and outerHTML swaps the row itself. Replacing it with an empty string removes it. hx-swap="delete" is the alternative that removes the target whatever the response contains. Be aware that hx-confirm uses the browser's confirm() dialog, which is blocked in our sandboxed preview, so test this one on a normal page.

Part 3: Together, and debugging

Exercise 9: Disable a button while loading

Combine both libraries: a "Load report" button uses HTMX to load /report into #report. While the request runs, the button must show "Loading..." and be disabled. Use hx-disabled-elt or an Alpine flag driven by HTMX events, your choice.

Show solution (HTMX only)
HTML
<button hx-get="/report" hx-target="#report" hx-disabled-elt="this"
        hx-indicator="this">
  <span class="idle">Load report</span>
  <span class="busy">Loading...</span>
</button>
<style>
  .busy { display: none; }
  .htmx-request .busy { display: inline; }
  .htmx-request .idle { display: none; }
</style>

hx-disabled-elt="this" sets disabled for the duration of the request. HTMX adds the htmx-request class to the element named by hx-indicator (here the button), which CSS uses to switch the labels.

Show solution (Alpine flag)
HTML
<div x-data="{ busy: false }"
     @htmx:before-request="busy = true"
     @htmx:after-request="busy = false">
  <button hx-get="/report" hx-target="#report" :disabled="busy"
          x-text="busy ? 'Loading...' : 'Load report'"></button>
</div>

HTMX events bubble, so the wrapper hears them. Alpine lets you write them in kebab-case with @htmx:before-request. See Using HTMX and Alpine.js Together.

Exercise 10: Debug the dead button

This page should load the message when you press the button, but nothing happens. Find the bug, then fix it.

Exercise 10: find the bug
Show solution

The target selector is misspelled: #mesage instead of #message. When hx-target matches no element, HTMX triggers an htmx:targetError event and swaps nothing. The fix is hx-target="#message". Open the browser console on a real page and you will see the error. More of these in Common Mistakes and Debugging.

Exercise 11: Debug the empty list

This Alpine list shows nothing and prints a console error. What is wrong, and how do you fix it?

HTML
<ul x-data="{ tags: ['css', 'html', 'js'] }">
  <li x-for="tag in tags" x-text="tag"></li>
</ul>
Show solution

x-for is only allowed on a <template> element. Alpine needs the template to clone for every item:

HTML
<ul x-data="{ tags: ['css', 'html', 'js'] }">
  <template x-for="tag in tags" :key="tag">
    <li x-text="tag"></li>
  </template>
</ul>

Also add :key so Alpine can track items when the list changes order.

Exercise 12: Server-driven badge, Alpine-driven panel

Build a mini notification bell. An Alpine component holds open (a panel that opens and closes). When the panel opens for the first time, it loads /notifications with HTMX into the panel, using hx-trigger="revealed" or an event, and the badge number next to the bell comes from the server fragment too.

Show solution
HTML
<div x-data="{ open: false }">
  <button @click="open = !open" :aria-expanded="open">
    Bell
    <span id="badge" hx-get="/notifications/count" hx-trigger="load"></span>
  </button>

  <div x-show="open" x-cloak
       hx-get="/notifications" hx-trigger="intersect once">
    Loading...
  </div>
</div>

The badge fetches itself with load, so the page can render instantly. The panel is hidden by Alpine (display: none), and HTMX's intersect trigger fires when an element becomes visible in the viewport. A hidden element never intersects, so the request starts the first time the panel opens, and once stops it from repeating. Alpine owns UI state (open or closed), HTMX owns server data (the list and the count). That split is the heart of this track.

Check your own progress

Count how many you solved without opening a solution: 10 or more means you are ready for the projects and real work; 6 to 9 means revisit the lessons linked from the exercises you missed; fewer than 6 is normal on a first pass, so read the lessons again, then retry.

Summary

  • Alpine exercises practiced x-data, :disabled, :class, getters, x-for on a <template> and .outside.
  • HTMX exercises practiced hx-get, hx-target, beforeend, delay:300ms, closest and hx-confirm.
  • Most bugs are small: a misspelled selector, a missing <template>, a missing x-data.
  • Give each library its own job: Alpine for the UI state, HTMX for server data.

Next: Common Mistakes and Debugging