htmx/www/content/examples/tabs-hyperscript.md
Denis Palashevskii 18aa2470a0
fix accesibility and keyboard navigation issues in examples (#1433)
* fix accesibility and keyboard navigation issues in examples

* fix review comments

* remove redundant aria attributes, remove redundant autofocus

* rework progress bar demo's accesibility

* rework tabs HATEOS example to be more ARIA compliant

* rework tabs _hyperscript example to be ARIA compliant
2023-06-30 11:28:54 -05:00

4.1 KiB

+++ title = "Tabs (Using Hyperscript)" template = "demo.html" +++

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" role="tablist" _="on htmx:afterOnLoad set @aria-selected of <[aria-selected=true]/> to false tell the target take .selected set @aria-selected to true">
	<button role="tab" aria-controls="tab-content" aria-selected="true" hx-get="/tab1" class="selected">Tab 1</button>
	<button role="tab" aria-controls="tab-content" aria-selected="false" hx-get="/tab2">Tab 2</button>
	<button role="tab" aria-controls="tab-content" aria-selected="false" hx-get="/tab3">Tab 3</button>
</div>

<div id="tab-contents" role="tabpanel" hx-get="/tab1" hx-trigger="load"></div>

{{ demoenv() }}

Tab 1 Tab 2 Tab 3