Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

More Than Click and Submit: Use Any Event with Stimulus

Stimulus actions can listen for more than clicks and form submissions. Learn how to use keyboard filters, global targets, listener options, parameters, and custom events.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Stimulus, the event name in a data-action descriptor determines what triggers a controller method. Replace click or submit with a DOM event the element dispatches—such as input, change, or keydown—and add keyboard filters, global targets, listener options, parameters, or custom events as needed. Stimulus connects those HTML annotations to controller methods; it does not replace the browser’s event system.

Change the event in the action descriptor

An explicit Stimulus action descriptor has the form event->controller#method. For example, click->gallery#next sends a click event to the next method of the controller identified as gallery. The event name is a DOM event name, so the same pattern handles other events when the chosen element dispatches them.

As an Amazon Associate I earn from qualifying purchases.

<input data-action="input->search#update">
<select data-action="change->filters#apply"></select>

Use input when a handler should respond as a text field’s value changes, and change when responding to a selection change. Stimulus also defines shorthand for common event-and-element pairs, including anchor and button clicks, details toggles, form submission, input and textarea input, and select changes. The full action reference lists the shorthand mappings and descriptor syntax: Stimulus Actions.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Filter keyboard events

Append a key filter to a keyboard event name to call the method only for a matching key. For example, keydown.esc->modal#close invokes the method on Escape. Available filters include Enter, Tab, Escape, space, arrow keys, Home and End, Page Up and Page Down, letters, and digits.

<div data-controller="modal" data-action="keydown.esc->modal#close">
  ...
</div>

Filters apply to keyboard events. You can combine a key with a modifier, as in keydown.ctrl+a->listbox#selectAll. If the key you need is not among the defaults, Stimulus lets an application configure custom key mappings through its schema. Check the action reference for the supported filters and configuration details: Stimulus Actions.

Listen on the window or document

When an event originates from a global object rather than a particular element, add @window or @document to the event name. For example, a gallery can respond to window resizing:

<div data-controller="gallery" data-action="resize@window->gallery#layout"></div>

Use a global target when the event’s source is the window or document, or when a listener must receive an event that does not bubble through the receiving controller’s element. For ordinary events on an element, attach the action there instead. The reference describes global targets and their syntax: Stimulus Actions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose listener options deliberately

Action descriptors can include native listener options and Stimulus-specific options. Put the option after the method, separated by a colon. These options change how the listener behaves; they do not change which event name it listens for.

Option Effect
:once Remove the listener after it runs once.
:capture Listen during the event’s capture phase.
:passive Register a passive listener.
:!passive Register a listener that is not passive.
:prevent Call preventDefault() before invoking the controller method.
:stop Call stopPropagation().
:self Invoke the method only when the event originated on the descriptor element.

For example, use :prevent when the browser’s normal action should be canceled before your method runs. Use :self when a bubbling event from a descendant should not trigger the action. Stimulus also allows applications to register custom action options with Application.registerActionOption; the reference demonstrates an option that checks whether a <details> element is open or closed. See the action option reference for syntax and behavior.

Read event data and pass per-element parameters

Stimulus passes the event object as the first argument to an action method. Its target is the element that dispatched the event; currentTarget is the element where the action listener was installed. The event also exposes information such as its type, and its methods include preventDefault() and stopPropagation().

For example, an input handler can inspect the event target’s value, while a keyboard handler can examine the key. If multiple actions handle the same event, Stimulus processes descriptors from left to right. Calling stopImmediatePropagation() prevents later actions for that same event from running.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For data that varies by element, put an action parameter attribute on the same element as the action. An attribute named data-item-id-param for the item controller makes the value available as event.params.id:

<button data-action="item#upvote" data-item-id-param="12345">Upvote</button>
upvote({ params: { id } }) {
  // use the per-element id
}

Stimulus infers parameter types, including numbers, strings, objects, and booleans. This lets one action method work with different values on different elements; the action reference documents the parameter naming and types. The Stimulus handbook also shows parameters used to pass different URLs to a content-loader action.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Send custom events between controllers

When one controller needs to notify another, use the controller’s dispatch helper to create a custom event. By default, the event name is prefixed with the dispatching controller’s identifier, and the payload is available in event.detail. A receiving controller can handle it with an action descriptor.

// In a clipboard controller
this.dispatch("copy", { detail: { content: text } })
<div data-controller="clipboard">
  <div data-controller="logger" data-action="clipboard:copy->logger#record"></div>
</div>

Dispatched events bubble by default, so an action on an ancestor along the event’s path can receive one. If the receiving element is outside that path, listen on a shared global target, such as @window. The dispatch helper accepts options including detail, target, prefix, bubbles, and cancelable; it returns the generated event, whose defaultPrevented property can be checked. Consult the Stimulus controller reference for dispatch behavior and options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Pick the pattern that matches the event

Need Pattern Key consideration
Respond to a field or selection changing input->search#update or change->filters#apply Choose an event the element actually dispatches.
Respond only to a particular key keydown.esc->modal#close Keyboard filters apply to keyboard events.
Handle a window or document event resize@window->gallery#layout Use @window or @document as appropriate.
Cancel browser behavior or restrict event propagation Add :prevent, :stop, or :self Each option has a distinct effect on the event.
Provide data that varies by action element data-[identifier]-[name]-param Read the typecast value from event.params.
Notify another controller Dispatch a custom event and handle its prefixed name Use a global listener if the receiver is outside the bubbling path.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.