Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created December 24, 2024 01:47
Show Gist options
  • Save dpaluy/fc5b53139e10c4c1244b1ad3e016413f to your computer and use it in GitHub Desktop.
Save dpaluy/fc5b53139e10c4c1244b1ad3e016413f to your computer and use it in GitHub Desktop.
Keyboard shortcuts for StimulusJS
// app/javascript/controllers/click_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
click() {
this.element.click()
}
}
<%# app/views/shared/_keyboard_shortcuts.html.erb %>
<! -- clicking "n" will click the link -->
<%= link_to "New Post", new_post_path,
data: {
controller: "click",
action: "keydown.n@window->click#click"
} %>
<! -- clicking "Ctrl+K" will click the link -->
<button data-controller="click"
data-action="keydown.meta+k@window->click#click keydown.ctrl+k@window->click#click">
Search
</button>
<! -- clicking "Cmd+Enter" will click the link -->
<button data-controller="click"
data-action="keydown.cmd+enter@window->click#click keydown.ctrl+enter@window->click#click">
Submit
</button>
@dpaluy
Copy link
Author

dpaluy commented Dec 24, 2024

search

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment