Tabs (Using Hyperscript)

This example shows how to load tab contents using htmx, and to select the "active" tab using Javascript. This reduces some duplication by offloading some of the work of re-rendering the tab HTML from your application server to your clients' browsers.

You may also consider a more idiomatic approach that follows the principle of Hypertext As The Engine Of Application State ..

Example Code

The HTML below displays a list of tabs, with added HTMX to dynamically load each tab pane from the server. A simple hyperscript event handler uses the take command to switch the selected tab when the content is swapped into the DOM. Alternatively, this could be accomplished with a slightly longer Javascript event handler.

<div id="tabs" hx-target="#tab-contents" _="on htmx:afterOnLoad take .selected for event.target">
	<a hx-get="/tab1" class="selected">Tab 1</a>
	<a hx-get="/tab2">Tab 2</a>
	<a hx-get="/tab3">Tab 3</a>
</div>

<div id="tab-contents" hx-get="/tab1" hx-trigger="load"></div>
Server Requests : 2 ↑ Show
GET /tab2
parameters: {}
Response

			<p>Kitsch fanny pack yr, farm-to-table cardigan cillum commodo reprehenderit plaid dolore cronut meditation. 
			Tattooed polaroid veniam, anim id cornhole hashtag sed forage. 
			Microdosing pug kitsch enim, kombucha pour-over sed irony forage live-edge. 
			Vexillologist eu nulla trust fund, street art blue bottle selvage raw denim. 
			Dolore nulla do readymade, est subway tile affogato hammock 8-bit. 
			Godard elit offal pariatur you probably haven't heard of them post-ironic. 
			Prism street art cray salvia.</p>
		 
...

Demo

Tab 1 Tab 2 Tab 3

Kitsch fanny pack yr, farm-to-table cardigan cillum commodo reprehenderit plaid dolore cronut meditation. Tattooed polaroid veniam, anim id cornhole hashtag sed forage. Microdosing pug kitsch enim, kombucha pour-over sed irony forage live-edge. Vexillologist eu nulla trust fund, street art blue bottle selvage raw denim. Dolore nulla do readymade, est subway tile affogato hammock 8-bit. Godard elit offal pariatur you probably haven't heard of them post-ironic. Prism street art cray salvia.