| 1 |
--- |
| 2 |
title: "Tabs" |
| 3 |
description: Switch between content panels using tabs |
| 4 |
icon: "icon-[mdi--tab]" |
| 5 |
soon: true |
| 6 |
--- |
| 7 |
Switch between content panels. Two approaches: server controls tab state, or JavaScript does. |
| 8 |
|
| 9 |
## Server-Driven (HATEOAS) |
| 10 |
|
| 11 |
The server controls which tab is selected. This follows [HATEOAS](https://en.wikipedia.org/wiki/HATEOAS) (Hypertext As The Engine Of Application State) - the server returns complete UI state with each response. |
| 12 |
|
| 13 |
```html |
| 14 |
<!-- Initial container --> |
| 15 |
<div id="tabs" hx-get="/tab1" hx-trigger="load"></div> |
| 16 |
``` |
| 17 |
|
| 18 |
```html |
| 19 |
<!-- Server returns this for each tab click --> |
| 20 |
<div role="tablist"> |
| 21 |
<button hx-get="/tab1" role="tab" aria-selected="true">Tab 1</button> |
| 22 |
<button hx-get="/tab2" role="tab" aria-selected="false">Tab 2</button> |
| 23 |
<button hx-get="/tab3" role="tab" aria-selected="false">Tab 3</button> |
| 24 |
</div> |
| 25 |
|
| 26 |
<div role="tabpanel"> |
| 27 |
Tab content here... |
| 28 |
</div> |
| 29 |
``` |
| 30 |
|
| 31 |
## Client-Side |
| 32 |
|
| 33 |
JavaScript handles tab selection. Server returns content only. Uses `aria-selected` attribute to control styling. |
| 34 |
|
| 35 |
```html |
| 36 |
<div role="tablist" |
| 37 |
hx-target:inherited="#tab-contents" |
| 38 |
hx-on:htmx-after-on-load=" |
| 39 |
document.querySelector('[aria-selected=true]').setAttribute('aria-selected', 'false'); |
| 40 |
event.target.setAttribute('aria-selected', 'true'); |
| 41 |
"> |
| 42 |
<button role="tab" hx-get="/tab1" aria-selected="true">Tab 1</button> |
| 43 |
<button role="tab" hx-get="/tab2" aria-selected="false">Tab 2</button> |
| 44 |
<button role="tab" hx-get="/tab3" aria-selected="false">Tab 3</button> |
| 45 |
</div> |
| 46 |
|
| 47 |
<div id="tab-contents" role="tabpanel" hx-get="/tab1" hx-trigger="load"></div> |
| 48 |
``` |
| 49 |
|
| 50 |
Server returns just the content: |
| 51 |
|
| 52 |
```html |
| 53 |
<p>Your tab content...</p> |
| 54 |
``` |