Tabbed interface with Stimulus.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
div data-controller='tabs' data-tabs-index='1' | |
.tabs.is-boxed.is-marginless | |
ul | |
li data-target='tabs.tab' | |
a data={action: "tabs#change"} Tab 1 | |
li data-target='tabs.tab' | |
a data={action: "tabs#change"} Tab 2 | |
.tab.box data={target: 'tabs.tabPanel'} Tab panel 1 | |
.tab.box data={target: 'tabs.tabPanel'} Tab panel 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "stimulus" | |
export default class extends Controller { | |
static targets = [ "tab", "tabPanel" ] | |
initialize() { | |
this.showTab() | |
} | |
change(e){ | |
this.index = this.tabTargets.indexOf(e.target.parentNode) | |
this.showTab(this.index) | |
} | |
showTab() { | |
this.tabPanelTargets.forEach((el, i) => { | |
if(i==this.index){ | |
el.classList.remove('is-hidden') | |
} else { | |
el.classList.add('is-hidden') | |
} | |
}) | |
this.tabTargets.forEach((el, i) => { | |
if(i==this.index){ | |
el.classList.add('is-active') | |
} else { | |
el.classList.remove('is-active') | |
} | |
}) | |
} | |
get index() { | |
return parseInt(this.data.get('index')) | |
} | |
set index(value) { | |
this.data.set("index", value) | |
this.showTab() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment