Building Live Search Functionality: Part II

Adding keyboard shortcut for search

We have to click the search icon in the header to open the search overlay panel and the cancel icon to close it. We can add keyboard shortcuts for these actions. Let’s use the "S" key on the keyboard to open the search overlay and the "ESC" key to close it. We want the page to be on the lookout for the "S" or "ESC" key press and open and close the search panel when these keys are pressed.

These keypresses are events which need to be added to the events method in the Search class. We will add an event listener to the main document object which looks out for a keyup or keydown event and calls the keyPressed method when a key is pressed. Using bind we can make sure that within the keyPressed callback method, the this keyword refers back to the main object.

keydown vs. keyup

The keydown event is fired as soon as the key is pressed while the keyup event is fired as soon as the key is released.

Using keyup may create a laggy feeling if someone holds down on the key as the event won’t fire till the key is released. In such cases keydown is useful because it fires as soon as a key is pressed.

The keydown event fires the millisecond a key is pressed and sometimes it does not give the code a chance to update variables. Another downside of using the keydown event is that it will keep on firing as long as the user holds down a key.

Get hands-on with 1200+ tech skills courses.