DEV Community

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

Posted on • Originally published at railsdesigner.com

2

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?

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more