Key art image for D-Pad Navigation in a Web App 2.0

D-Pad Navigation in a Web App 2.0

A little over a year ago I wrote D-Pad Navigation in a Web App. The biggest problem was it required a lot of work to get things going, so I spent a few days rewriting some of the logic into a more friendly, generic library.

To support D-Pad navigation with this library, you need to do the following:

  1. Download the library’s javascript file from here:

  2. Import the javascript file into your page:

    <script src="./scripts/dpad-nav-lib.min.js" />
  3. Add a tabindex and class name dpad-focusable for any element you want to be focusable.

    For Example:

    <div class="grid-item dpad-focusable" tabindex="0">
    <img class="thumb" src="./images/thumbs/thumb01.jpg" />
    <div class="title">Item 1</div>
  4. Apply styling in your css for the focus pseudo class.

    .grid-item:focus {
    outline: none;
    background-color: rgb(149, 165, 166);
  5. Apply styling for when the user clicks on a focused element via the clickdown class.

    .grid-item.clickdown {
      background-color: rgb(189, 195, 199);

You should now be supporting D-Pad navigation.

onFocus Behaviour

Once an element receives focus, you can use the focus event to scroll it into view or perform some other action.

element.addEventListener('focus', function(e) {
  console.log('Element Focused');
}, true);

onClick Behaviour

When you want to detect when an element is clicked, you use the normal click event.

element.addEventListener('click', function() {
  console.log('Element Clicked');
}, true);


Adding and Removing Elements

The way the library works is that on page load or page resize, it will calculate the graph of where each nodes closest neighbours are, based purely on each elements position in the viewport.

What the library does not do, is recalculate the graph if you add or remove elements. To support this, you need to update the elements in the graph and their connections, which is done by calling:


Tabindex and Browser Focus

With the tabindex property you can determine the order in which a view is focused when you hit the tab key. The ordering is ignored by this library, tabindex is needed to ensure the browser allows an element to gain focus, however the order will still be applied if you hit tab on the keyboard.


There is a debug option to display lines which indicate the link between each node.


D-Pad Navigation Library in Debug Mode

Be Gentle…

This is a first attempt at the library and I’ve only created simplistic tests so if you give it a go, please post issues and feature requests here:

And one last thing, pull requests are more than welcome :)

Orig Photo: