How to Toggle Multiple CSS Classes with Stimulus

A hand choosing multiple classses in an abstract-illustration style

Adding and removing (or “toggling”) CSS classes is a common thing to do in web apps. From showing an element with hidden (display: none) to block (display: block). To adding a class that cascades down the DOM, ie. adding a dark class to the body-element.

Sometimes you want to add multiple classes to an element. A good example is this site’s navigation: after a certain scroll amount, bg-white/60 backdrop-blur-md both are added to the nav-element (giving that glass-like look).

This is done using Stimulus’ dedicated Classes API.

The most simplest use would be the following:

<nav data-controller="navigation" data-navigation-scrolling-class="block">

Then in the navigation_controller.js you can use it like so:

export default class extends Controller {
  static classes = ["scrolling"];

  scroll() {
    // after some threshold/instantiating an IntersectionObserver

    this.element.classList.toggle(this.scrollingClass);
  }
}

This is using the classlist toggle feature. All great, but what about the example above, where you want to add multiple CSS classes? toggle, and both add and remove methods of the Dom ClassList API allow you to add (an array) of classes.

// …
scroll() {
  this.element.classList.add("bg-white/60", "backdrop-blur-md");
}
// …

But if you try to add these as a value to the scrolling class, you notice it fails.

<nav data-controller="navigation" data-navigation-scrolling-class="bg-white/60 backdrop-blur-md">

What’s the solution?

Passing multiple classes using the Classes API

Stimulus has you covered! Use the plural name (this.scrollingClasses) instead of the singular name (this.scrollingClass). Combine this with the spread syntax (...) and you’re off to the races.

// …
scroll() {
  this.element.classList.add(...this.scrollingClasses);
}
// …

Pretty clean solution, don’t you think?

Get UI & Product Engineering Insights for Rails Apps (and product updates!)

Published at . Last updated at . Have suggestions or improvements on this content? Do reach out.

UI components for Ruby on Rails apps

$ 129 one-time
payment

Get Access
  • One-time Payment

  • Access to the Entire Library

  • Built for Ruby on Rails (inc. Rails 8)

  • Designed with Tailwind CSS and Enhanced with Hotwire

  • Updates for 12 months