mirror of
				https://github.com/bigskysoftware/htmx.git
				synced 2025-11-03 23:13:37 +00:00 
			
		
		
		
	
		
			
				
	
	
	
		
			4.7 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			4.7 KiB
		
	
	
	
	
	
	
	
+++ title = "Tabs (Using JavaScript)" 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
JavaScript event handler uses the take function to switch the selected tab
when the content is swapped into the DOM.
<div id="tabs" hx-target="#tab-contents" role="tablist"
     hx-on:htmx-after-on-load="let currentTab = document.querySelector('[aria-selected=true]');
                               currentTab.setAttribute('aria-selected', 'false')
                               currentTab.classList.remove('selected')
                               let newTab = event.target
                               newTab.setAttribute('aria-selected', 'true')
                               newTab.classList.add('selected')">
    <button role="tab" aria-controls="tab-contents" aria-selected="true" hx-get="/tab1" class="selected">Tab 1</button>
    <button role="tab" aria-controls="tab-contents" aria-selected="false" hx-get="/tab2">Tab 2</button>
    <button role="tab" aria-controls="tab-contents" 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