I stand up for children in need. Please join me in helping this family.

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.

More posts

Life as a Sonnet: Madeleine L'Engle's Poetic Wisdom

Madeleine L'Engle's quote from "A Wrinkle in Time" compares life to writing a sonnet, highlighting the balance between structure and creativity. It emphasizes personal responsibility in shaping our lives within given constraints.

Enhancing User Experience with Laravel Precognition

Laravel Precognition enables real-time form validation using server-side rules. It integrates with frontend frameworks like Vue.js to provide immediate feedback. Key uses include multi-step forms, dynamic field validation, debounced validation, and file upload checks. Best practices involve maintaining backend validation, handling network errors, and considering performance implications.

"Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do."

Steve Jobs BrainyQuote