Declarative keyboard navigation

Encapsulate the details of handling key events in a tidy reusable component.

Summary

Power users love keyboard navigation, but it's often an overlooked feature. Keyboard nav is almost never present in designs or mockups, and the last thing UI developers want to do is juggle keyboard events.

What if there was an easy way to add keyboard navigation to your application? In this video, we'll create a declarative and composable component that makes keyboard navigation painless.

{{! use the J and K keys to navigate through the list of posts }}

{{keyboard-press
  key="KeyJ"
  on-press=(action (mut navigatedPost) (next navigatedPost posts))}}

{{keyboard-press
  key="KeyK"
  on-press=(action (mut navigatedPost) (previous navigatedPost posts))}}

{{keyboard-press
  key="Enter"
  on-press=(action "openPost" navigatedPost)}}

We'll first need to install ember-keyboard in order to make this API work.

ember install ember-keyboard

Next, we can create the keyboard-press component.

import Component from '@ember/component';
import { EKMixin, keyDown } from 'ember-keyboard';

export default Component.extend(EKMixin, {
  key: null,
  'on-press'() {},

  didInsertElement() {
    this._super(...arguments);

    let key = this.get('key');
    let action = this.get('on-press');

    this.set('keyboardActivated', true);

    this.on(keyDown(key), action);
  }
});

👋 Hey there, Ember dev!

We hope you enjoyed this free video 🙂

If you like it and want to keep learning with us, we've written a free 6-lesson email course about the fundamental patterns of modern component design in Ember.

To get the first lesson now, enter your best email address below:

You can also check out more details about the course by clicking here.

Questions?

Send us a tweet:

Or ask us in Inside EmberMap, our private Slack workspace for subscribers.