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);
  }
}

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?

Rails Designer is a professional UI components library for Rails

Get product updates, insights and latest articles in your inbox

Published at . Last updated at . Have suggestions or improvements on this content? Do reach out. Interested in sharing Rails Designer with the Ruby on Rails community? Become an affiliate.

UI components for Ruby on Rails apps

$ 99 one-time
payment

Get Access
  • One-time payment

  • Access to the entire library

  • Built for Ruby on Rails

  • Designed with Tailwind CSS and enhanced with Hotwire

  • Includes free updates (to any 1.x version)