How to Create a Stimulus Toggle Class Controller

Published at Leave your comment

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>

💬 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

More articles like this on modern Rails & frontend? And the odd sneak peek?
JavaScript for Rails Developers
Make JS your 2nd favorite language