Hide and show elements with Stimulus
Summary
Easy and reusable controller to hide and show elements on interactionLesson
Sometimes, some HTML elements should only be shown or hidden after another interactions. This small Stimulus Controller makes this very easy to wire up and only needs one CSS class to be defined a bit further down (the controller also works with Tailwind with the same hidden
class that is toggled).
// app/javascript/controllers/display_toggle_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="display-toggle"
export default class extends Controller {
static targets = ["element"]
toggle(event) {
this.elementTargets.forEach(element => {
element.classList.toggle("hidden")
})
}
}
The CSS class that makes the above work is simple:
.hidden {
display: none;
}
Below is an example of how this might be used; I toggle my User menu with it.
The display-toggle
controller wraps everything, put the action on the toggling button(s), and mark the elements to be hidden/shown with the attributes data-display-toggle-target="element"
. There can also be more than one that will be toggled.
<div class="user-menu" data-controller="display-toggle">
<button data-action="display-toggle#toggle">
Avatar icon
</button>
<div class="user-menu__content hidden" data-display-toggle-target="element">
<ul>...</ul>
</div>
</div>
A useful trick to make the styling of the menu more convenient without the need to always click to toggle after a page reload...just remove the hidden class while working on the component.