# Practical Stimulus: How to Toggle CSS Classes

*Published on June 11, 2023*

Tags: Hotwire

---


CSS classes offer an easy way for changing styles and playing animations dynamically. Often, you want to add or remove certain classes in response to user actions. For example, imagine you want to highlight a paragraph when the user selects a checkbox. See [this video](https://vimeo.com/835112759)for a quick demo.

Let's first implement this feature in plain JavaScript, so we can compare it against the corresponding Stimulus version.

Here's the HTML which adds a checkbox and a paragraph.

```html
<div>
  <input type="checkbox" id="admin-checkbox">
  <label for="admin-checkbox">Highlight</label>
</div>

<p id="message">Some Text</p>
```

Next, let's add a new class called&nbsp;`highlight`, which we'll use to highlight the paragraph.

```css
.highlight {
    background-color: yellow;
 }
```

Finally, we'll write the JavaScript that listens to the&nbsp;`change`&nbsp;event on the checkbox and toggles the&nbsp;`highlight`&nbsp;class on the paragraph.

```javascript
const highlighter = document.getElementById("admin-checkbox")
  
highlighter.addEventListener("change", () => {
  const paragraph = document.getElementById("message")
  paragraph.classList.toggle("highlight")
})
```

This works as expected. Plain and simple. Now let's learn how you might implement this in Stimulus.

## Step 1: Wrap HTML in Controller Attribute

As we saw in&nbsp;[the previous article](/practical-stimulus-capture-user-input), Stimulus controllers restrict the scope and componentize our HTML. First, we'll wrap the HTML in a controller data attribute.

```html
<div data-controller="highlight">
  <div>
    <input type="checkbox" id="admin-checkbox">
    <label for="admin-checkbox">Highlight</label>
  </div>

  <p>Some Text</p>
</div>
```

When the HTML loads, Stimulus will look for a corresponding controller class, which we'll add next.

## Step 2: Create a Stimulus Controller

Let's generate a controller class using the Rails generator.

```bash
➜ bin/rails generate stimulus highlight
    create  app/javascript/controllers/highlight_controller.js
```

This adds a new JavaScript file called&nbsp;`highlight_controller.js`&nbsp;under the&nbsp;`app/javascript/controllers`&nbsp;directory. This is where the logic to toggle the classes will live.

```javascript
import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="highlight"
export default class extends Controller {
  connect() {
  }
}
```

To modify the classes on the paragraph element, we need a handle on it. We'll use Stimulus targets to accomplish this.

## Step 3: Identify Elements with Targets

Stimulus Targets let us reference important elements by their names, instead of classes or IDs. We'll add a data attribute on the&nbsp;`<p>`&nbsp;element to identify it with a logical name.

```html
<p data-highlight-target="paragraph">Some Text</p>
```

For each target, we need to create a corresponding target property in the JavaScript controller. See the documentation for&nbsp;[Stimulus Targets](https://stimulus.hotwired.dev/reference/targets)&nbsp;for more details.

```javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "paragraph" ]

  connect() {
    console.log(this.paragraphTarget)  // paragraph element
  }
}
```

Next, we want to listen to the&nbsp;`change`&nbsp;event on the highlighter checkbox. We'll use&nbsp;[Stimulus Actions](https://stimulus.hotwired.dev/reference/actions)&nbsp;to accomplish this.

## Step 4: Listen to Checkbox Change Event with Actions

As we saw in the previous article, Actions use conventions to attach event handlers, instead of us having to write JavaScript code to attach them. For this, we'll add a new data attribute on the highlighter checkbox as follows:

```html
<input type="checkbox" id="admin-checkbox"
       data-action="change->highlight#update">
```

The&nbsp;`data-action`&nbsp;value&nbsp;`change->highlight#update`&nbsp;uses the following conventions:

- `change`&nbsp;is the name of the DOM event to listen for on the checkbox
- `highlight`&nbsp;is the controller identifier
- `update`&nbsp;is the name of the method to invoke

When you check or uncheck the highlighter checkbox, Stimulus will call the&nbsp;`update`&nbsp;method in the&nbsp;`highlight_controller.js`&nbsp;file.

Now let's add the&nbsp;`update`&nbsp;method on the controller which will toggle the classes.

```javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "paragraph" ]

  update() {
    console.log('toggle classes here')
  }
}
```

If you launch the site in the browser and check or uncheck the highlighter checkbox, you'll notice the above message in the console.

The only thing that's remaining now is to toggle the&nbsp;`highlight`&nbsp;class when the user checks or unchecks the highlighter checkbox. For this, we'll use the&nbsp;[Stimulus Classes](https://stimulus.hotwired.dev/reference/css-classes)&nbsp;API, which lets us reference classes by name.

## Step 5: Declare Classes as Stimulus Class Attributes

> Instead of hard-coding classes with JavaScript strings, Stimulus lets you refer to CSS classes by&nbsp;_logical name_&nbsp;using a combination of data attributes and controller properties.

In our case, we want to toggle the class&nbsp;`highlight`&nbsp;on the paragraph element. So we'll declare this class in the HTML, on the same element where we created our controller.

```html
<div data-controller="highlight" data-highlight-toggle-class="highlight">
  <!-- rest of the HTML -->
</div>
```

The attribute takes the form of&nbsp;`data-[controller]-[logical_name]-class`&nbsp;and Stimulus lets you refer to the classes by their logical names inside the controller.

```javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "paragraph" ]
  static classes = [ "toggle" ]

  update() {
    console.log(this.toggleClass)  // highlight
  }
}
```

Now that we have a handle on the&nbsp;`toggleClass`, we'll use the JavaScript&nbsp;[classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)&nbsp;property to toggle the class name as follows:

```javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "paragraph" ]
  static classes = [ "toggle" ]

  update() {
    this.paragraphTarget.classList.toggle(this.toggleClass)
  }
}
```

And that's it. If you click the checkbox, it will toggle the&nbsp;`highlight`&nbsp;class on and off on the paragraph element.

Here's the final HTML.

```html
<div data-controller="highlight" data-highlight-toggle-class="highlight">
  <div>
    <input type="checkbox" id="admin-checkbox" data-action="change->highlight#update">
    <label for="admin-checkbox">Highlight</label>
  </div>

  <p data-highlight-target="paragraph">Some Text</p>
</div>
```

If you have multiple classes that you need to access, just add them all in the data attribute, and Stimulus will make them all available in an array named&nbsp;`this.[logicalName]Classes`&nbsp;property in the controller. In addition, you can check if an element already has a class with the&nbsp;`this.has[logicalName]Class`&nbsp;property. For more details, check the&nbsp;[Classes documentation](https://stimulus.hotwired.dev/reference/css-classes).

The nice benefit of using the Stimulus classes API is that your classes live in HTML, not in JavaScript. And you get to refer to the classes by their logical names. This frees your designers to modify the class names without developers having to update the corresponding classes in JavaScript. This pairs really well with Tailwind CSS as well.

That's it for today. In the next article in this series, we'll learn how you can submit a form using Stimulus. Stay tuned!

