Shortcuts using Alpine JS

I must say that I love shortcuts or keymaps, I have greate influence about it for using vim from a long time.

Saying that I wanted to implement a shortcut to be able to got to the search input box simply by typing slash / or cmd + k.

When I first thought about implementing Vanilla JS came to mind after that probably using a library for this. I made my investigation and I found pretty slick library called hotkeys.js, you should check it out.

But.... since I´m using Alpine JS for everything lately and this blog is using it. I try to find out a way to do it. And I think it will surprise you how easy it is to implement it.

This is the simple version of it. The init() function is used to initialize the functions search() and home().

  • search() will give the focus to the search input control
  • home() will redict the page to home.
<script>
function init(){
    return {
        search() {
            setTimeout(() => {
            this.$refs.q.focus()
            }, 100)
        },
        home() {
            window.location.href = '/'
        }
    }
}
window.init = init
</script>
<nav x-data="init()"
    @keydown.window.slash="search()" 
    @keydown.window.prevent.ctrl.k="search()"
    @keydown.window.prevent.ctrl.h="home()" 
>
...
<form>
    <input x-ref="q" type="search" placeholder="Search /, ctrl + k">
</form>
</nav>

Victor Yoalli

This is me.