How to Implement Hot Keys with System Modifier Keys in Vue JS
So far in this section of the course, we've walked through a number of different event listeners that we can implement. Now I want to show you how we can implement an event listener that actually listens for hotkeys.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So this may or may not be something that you will need to implement. But what I've found is that this is a really cool way of being able to add easter eggs to a program.

Say that you have some kind of application and you want to add some fun ways for users to access secret or cool hidden features in the app or you may just have a really practical need for that.

So say you're building out an application that you want to act a little bit more like a native app then this is also a way of doing that.

So what we have here is the ability to tack on some custom hardware event listeners so some modifier keys so these are typically keys like control+alt+shift and some of those and you can listen specifically for those.

So inside of index.html I'll put a new div here, and I'm going to add in<h2>Hot Keys</h2>, then I'm going to add a button.

index.html

<div>
    <h2>Hot Keys</h2>

    <button @click.shift="hotKey">You clicked a button with shift</button>
</div>

Now let's add that inside of app.js.

app.js

hotKey() {
    console.log('Hot Key was pressed');
}

Save that and now let's come back. Right here I do have a list for you so you can see inside the Vue.js documentation (link below), you can see all the system modifier keys and so you have access to control alt shift and Meta.

Now one thing I will say is, while this is helpful, I would really be careful with a few of these. So control, alt, and Meta are going to be a little bit dependent on your users' hardware.

Really the only time I ever use this is with the shift key and it's because that's something that all systems have access to. Control tends to get overridden by certain applications and programs. Alt does not work on all operating systems.

Same thing with meta. Shift is the only one I've found to work across the board. That's just my personal opinion and my experience. But I would definitely give you that as a caveat.

So right now if I come here to our hotkeys section and click on this,

large

you can see even though we added that console log statement nothing is happening. But now if I press down the shift key and then click it you can see that now on the right-hand side everything is activated.

large

The only time this is going to work now is when I have the shift key pressed. If shift isn't pressed, the button will not work. So that is how you can implement a click listener and then tack on a specific key modifier so that you can add some functionality into your app.

Resources