How to Create a Stimulus Toggle Class Controller
Toggling CSS classes on elements is a really common thing to do in webapps. Stimulus makes this really easy. This is the full controller:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static classes = ["toggle"]
toggle() {
this.element.classList.toggle(...this.toggleClasses)
}
}
And you use it like this:
<button data-controller="toggle-class" data-toggle-class-toggle-class="show-button">
Click me
</button>
You can pass it multiple classes too, great if you use Tailwind CSS. See this article about toggling multiple classes for more details on how this works.
<button data-controller="toggle-class" data-toggle-class-toggle-class="border-gray-200 shadow-xl" class="border shadow-lg">
Click me
</button>
Want to read me more?
-
How to Toggle Multiple CSS Classes with Stimulus
Looking to add multiple CSS classes with Stimulus? Easy using Stimulus' Classes API -
Stimulus Features You (Didn't) Know
Stimulus is advertised as a modest JavaScript framework, but packs still quite a few features. Lets explore the lesser known ones. -
New: Rails Development Tool
New from Rails Designer: the Rails Development Tool. Improve your Rails development efficiency.
Over to you…
What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!
Comments are powered by Chirp Form
{{comment}}