Skip to Content

Pager keys for Drupal and Views

About a half hour ago I found a really great script on Github for quickly browsing posts on a page. If you are on the homepage of my site, try typing the following hotkeys:

Key Action
h Next page
j Next post
k Previous post
l Previous page

If you have used the hotkeys in GMail or Google Reader, you will have likely used these shortcuts before. This usability pattern is showing up in quite a few places and I really like it. Take a look at how effective it is for browsing images on The Big Picture (make sure you're on a post), on Flickriver, and on FFFFOUND!.

Drupal is a great candidate for this pattern since quickly browsing through a list of nodes is quite common. Also, since Drupal comes with jQuery, adding the script wasn't too difficult. Here are some small adjustments to make it work.

This guide assumes that you are using Views to generate a list of nodes but it should be easy to adapt to other situations.

  1. Snag the jQuery version provided on Git and save it to your theme's directory.
  2. Add the page_keys.js to Drupal by adding the line scripts[] = paging_keys.js to your theme's .info.
  3. We have to make a few small adjustments to the script to make it play nice with Drupal. Go take a look at the settings array found on line 84 of paging_keys.js. Let's change it to the following:

    var config = {
      nodeSelector: '#main .node h2.node-title a',
      prevPageSelector: '.pager-previous a',
      nextPageSelector: '.pager-next a',
      pagingNavId: 'paging-nav',
      keyNext: 'j',
      keyPrev: 'k',
      keyNextPage: 'h',
      keyPrevPage: 'l',
      keyRefresh: 'r',
      additionalBodyClass: 'paging-keys',
      bottomAnchor: 'bottom'
    };

    This assumes that the list of nodes will be under the div '#main', but you will probably want to change this to be more specific. For my own site I've also used the view name in the selector to ensure that there is not any weird behaviour. The only other changes to the config array were for the Drupal pager.

  4. We want to add the anchor "bottom" to the last node of the View, allowing the script to move nicely between pages. To do this, we can add a small snippet to the node title link in node.tpl.php. Here is what my revised node title code looks like:

    <h2 class="title node-title">
      <a href="<?php echo $node_url; ?>"<?php if($view) { end($view->result)->nid == $node->nid ? print 'name="bottom"' : NULL; } ?>><?php echo $title; ?></a>
    </h2>

    This will check if we are displaying the last node for this view and add 'name="bottom"' to it's title link.

And you are done! Hopefully everything is working great. If you encounter problems, make sure that caching is turned off while you try to integrate this.