Creating an Action

Let's create an action in this lesson!

Connecting a DOM event to the controller

In Stimulus, an action connects a DOM event to the controller code that you want executed when that event happens. Like controllers, Stimulus actions are also defined using a data attribute in the markup: you add the attribute to the DOM element whose events you want to watch. In our case, that’s the div element we have styled as a button:

<div class="button is-primary js--day-button"
     data-action="click->day-toggle#toggle">
  <span class="js--button-text">Hide</span>
</div>

The new line defining the actions is data-action="click->day-toggle#toggle". The data-action is the attribute name that signals to Stimulus that an action is being defined. The value of the data-action attribute is a little mini-language to define the connection between the event and the code.

The mini-language, which Stimulus calls an action descriptor, has three parts:

  • The first element is the name of the event being watched for, which in our case is click, followed by an arrow (->). The event can be any DOM event!
  • The second element is the name of the controller, spelled exactly the way the name is spelled where the controller is defined, meaning that it’s dash-case. For us, that’s day-toggle. This element ends with a hash (#).
  • The last element is the name of the method to be called on the controller when the event happens. This needs to be the exact name of the method, which usually means it’s in camelCase. (I’m not sure why Stimulus doesn’t chose to translate to camelCase here). Our method is toggle.

So, an action descriptor consists of three-parts: an action, a controller, and a method. When it sees a data-attribute method, Stimulus sets up a listener on the event which executes the named method on the controller when the event fires. If there are multiple instances of controllers with that name, the instance representing the closest ancestor to the element triggering the event is the instance that executes the method.

Default Events
I don’t really recommend it, but Stimulus allows you to leave off the event name for the “default” event of specific elements. If your element is a, button, or input[type="submit"], then the default action is click, and you can respond to a click event with just the controller name and method, as in "day-toggle#toggle". (We can’t use that in our code, because our element is a div not an HTML button.) If the element is any other kind of input, a select, or a textarea, then the default event is change, and for a form, the default event is submit. I find the consistency of keeping the event around to be worth the extra typing, however. As per the official Stimulus documentation, the event can be any DOM event object.

Having created an action descriptor that references a toggle method, we need to write a corresponding toggle method in our controller:

Get hands-on with 1200+ tech skills courses.