I'm making a course on Laravel Sanctum: MasteringAuth.com

Open the modal using a keyboard shortcut

Constantin Druc ยท 30 Dec, 2021

[00:00] I don't know if you noticed, but as soon as we've added the Dialog and DialogOverlay components, the button shrank back to its initial size.

[00:09] Previously we only had the button element and vue knew how to bind the class attribute to it. Now that we have two elements, we need to be more specific and tell vue to which element to bind the attributes passed to the component. We want to bind the class attribute to the button element, so we'll say v-bind="$attrs" attributes, save,and here it is; our button is white again.

[00:34] Our modal closes when we click on the overlay or press the escape key, but currently, there is no way to open the modal. I would like it to open when I click on the search button or use the command+k shortcut. Let's tackle the first one.

[00:47] Here, on the button we'll do @click and set isOpen to true. And here it is, open, close, open, close. Now for the keyboard shortcut, we can go to our setup function and tap into the unmounted hook. Here we can add an event listener for the keydown event. We'll do window add event listener, keydown, function, and we'll receive the event as argument. Then, we can check if the modal is already opened, and if that's the case, we just return early; otherwise, we continue checking if the pressed keys match our expected combination.

[01:27] So if event meta key, or event control key, and this matches the command key on mac or the control key, and event.key == 'k', then we set the isOpen value to true, which will open the modal.

[01:42] Let's extract this into a function. I'll cut this and say onkeydown, and here I'll do const onkeydown, and paste in the function. Then, when the component is unmounted, we'll remove the event listener. So window, remove event listener, key down, on key down. If we go in the browser we can open the modal by clicking on it. Let's close it, and now, I am on a mac device, so if I press command+k, the modal opens. Isn't that nice?