Skip to content

Commit

Permalink
Update 2022-07-20-stimulusjs-tabs.md
Browse files Browse the repository at this point in the history
  • Loading branch information
yshmarov committed Feb 27, 2024
1 parent 0cef5de commit 04403d8
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions _posts/2022-07-20-stimulusjs-tabs.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,18 @@ HOWTO:
rails g stimulus tabs
```

install `stimulus-use` to add the "click outside to close tab(s) behaviour:

```sh
bin/importmap pin stimulus-use
```

2. the stimulus controller:

```js
// app/javascript/controllers/tabs_controller.js
import { Controller } from "@hotwired/stimulus"
import { useClickOutside } from "stimulus-use";

// Connects to data-controller="tabs"
export default class extends Controller {
Expand All @@ -51,6 +58,7 @@ export default class extends Controller {
selectedTab.hidden = false
selectedBtn.classList.add("active")
} catch { }
useClickOutside(this)
}

select(event) {
Expand All @@ -70,6 +78,11 @@ export default class extends Controller {
event.currentTarget.classList.remove("active") // deactive current btn
}
}

clickOutside() {
this.tabTargets.forEach(x => x.classList.add("hidden")); // hide all tabs
this.btnTargets.forEach(x => x.classList.remove("active")); // deactivate all btns
}
}
```

Expand All @@ -91,9 +104,9 @@ export default class extends Controller {

```html
<div data-controller="tabs" data-tabs-default-tab-value="two">
<button id="one" data-tabs-target="btn" data-action="click->tabs#select">UK</button>
<button id="two" data-tabs-target="btn" data-action="click->tabs#select">France</button>
<button id="abc" data-tabs-target="btn" data-action="click->tabs#select">Ukraine</button>
<button type="button" id="one" data-tabs-target="btn" data-action="click->tabs#select">UK</button>
<button type="button" id="two" data-tabs-target="btn" data-action="click->tabs#select">France</button>
<button type="button" id="abc" data-tabs-target="btn" data-action="click->tabs#select">Ukraine</button>
<div data-tabs-target="tab" id="one">
London, Glasgow
</div>
Expand Down

0 comments on commit 04403d8

Please sign in to comment.