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>