Skip to content
Steven Roland

Keyboard Shortcuts with Alpine.js

I just added an Alpine.js-powered search to a website and, as part of that update, I wanted to add a keyboard shortcut to make it super easy and fast to open the search input. It was my first time doing something like this with Alpine.js and it was so much easier than I expected. Here's how I got it done:

I've extracted all the search functionality to a javascript component, but you can implement this pretty easily inline as well.

export default () => ({
     searching: false,
     showInput() {
         this.searching = true;
     },
});

The important part of this code is setting the searching variable to true when showInput() is called.

<div x-data="search" x-on:keydown.window.prevent.ctrl.slash="showInput()">
     <input x-ref="search" >
</div>

Notice the x-on:keydown.window.prevent.ctrl.slash part of this snippet. Alpine.js makes handling keyboard input very straightfoward. In the HTML, all we need to do is target the keydown event for a specific key, like enter or k. I wanted to make sure opening the search is more intentional though, so I opted for a combination of keys, while preventing any default behavior.

Support My Work

If you enjoy my content, consider supporting me through Buy Me a Coffee or GitHub Sponsors.

Buy Me A Coffee
or

More posts

Laravel's email Validation Rule: Ensuring Valid Email Addresses

This post explains Laravel's email validation rule, its usage, and provides real-world examples for user registration, newsletter subscription, and contact form submission. It also covers advanced usage, error handling, and best practices for email validation.

Using CSRF Tokens with AJAX in PHP

Secure AJAX requests in PHP by implementing CSRF tokens, ensuring each asynchronous submission is authorized and protected against attacks.