Skip to content

Instantly share code, notes, and snippets.

@ryenski
Last active January 13, 2022 04:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryenski/3e6f731c053103cdbc7b6f702ba080f8 to your computer and use it in GitHub Desktop.
Save ryenski/3e6f731c053103cdbc7b6f702ba080f8 to your computer and use it in GitHub Desktop.
Tabbed interface with Stimulus.js
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
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()
}
}
@ryenski
Copy link
Author

ryenski commented Feb 8, 2018

@nick-symon
Copy link

Thanks for sharing! This was super helpful! I used it in my own application. The only change is now using the value attribute api for getting/setting the index value

@vietxenia
Copy link

Thanks for your sharing! This is useful to me.
I updated some based on your function so that we could use TabPanl by ID.
https://codepen.io/koolsolutions/pen/XWRJqLe
Thank you! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment