Stimulus Keyboard Event Filter

JetThoughts
JTWay
Published in
2 min readDec 20, 2023

--

New StimulusJS Global Events for Keyboard

In the last update of Stimulus v3.2.2, the ability to filter the event by PageDown and PageUp keys were added.

Before Stimulus v3.2.2

Before that, in v3.2.1, it looked like this:

<div data-action="keyup->myController#myfunction"></div>

and some like this…

import { Controller } from "stimulus";

export default class extends Controller {
connect() {
// Add a keydown event listener when the controller is connected to the DOM
document.addEventListener("keydown", this.handleKeyDown);
}

disconnect() {
// Remove the keydown event listener when the controller is disconnected
document.removeEventListener("keydown", this.handleKeyDown);
}

handleKeyDown(event) {
// Access the pressed key from the event
const pressedKey = event.key;

// Do something with the pressed key
console.log(`Pressed key: ${pressedKey}`);
}
}

From Stimulus v3.2.2

From now, you can call page_up/page_down in action, like:

<div data-action="keydown.page_up->myController#myfunction"></div>

The update appears to introduce a more declarative syntax for handling keyboard events in Stimulus. Instead of manually adding and removing event listeners in the controller, you can directly specify the key and event type in the HTML using the data-action attribute.

For example, in the updated version, the element is set to trigger the function method in myController, specifically on a key-down event for the Page Up key. This makes the code cleaner and more readable, emphasizing the intent directly in the HTML markup.

--

--