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">
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?
Top comments (0)