DEV Community

Cover image for How to Toggle Multiple CSS Classes with Stimulus
Rails Designer
Rails Designer

Posted on • Originally published at railsdesigner.com

How to Toggle Multiple CSS Classes with Stimulus

This article was originally published at Rails Designer.


Adding and removing (or “toggling”) CSS classes is a common thing to in web applications. 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 Rails Designer's site 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">
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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");
}
// …
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

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);
}
// …
Enter fullscreen mode Exit fullscreen mode

Pretty clean solution, don't you think?

Top comments (0)