Keyboard shortcuts in Drupal: Navigating through comments

Dec 14 2008 Published by Eneko Alonso under uncategorized

It was one of the best features of Google Reader and Google GMail: the keyboard shortcuts, specially the ones to navigate through messages or posts (n = next, p = previous).

I decided it was time to implement it on spaniards.es, so here is the code I used. So far it only navigates through comments back and forth on the same page (does not go to next page or so). I am planning to add other shortcuts soon.

  1. $(document).keyup(function(event) {
  2.  
  3.   if (event.target.tagName == "INPUT" ||
  4.       event.target.tagName == "TEXTAREA")
  5.     return;
  6.  
  7.   var selected = $('.comment-selected');
  8.  
  9.   // Next comment
  10.   if (event.keyCode == 78) {
  11.     if (selected.length) {
  12.       selected.removeClass('comment-selected');
  13.       selected = selected.nextAll('.comment:first');
  14.       selected.addClass('comment-selected');
  15.     } else {
  16.       selected = $('.comment:first').addClass('comment-selected');
  17.     }
  18.     if (selected.length) {
  19.       window.scrollTo(0, selected.offset().top);
  20.     }
  21.     return;
  22.   }
  23.  
  24.   // Previous comment
  25.   if (event.keyCode == 80) {
  26.     if (selected.length) {
  27.       selected.removeClass('comment-selected');
  28.       selected = selected.prevAll('.comment:first');
  29.       selected.addClass('comment-selected');
  30.     } else {
  31.       selected = $('.comment:last').addClass('comment-selected');
  32.     }
  33.     if (selected.length) {
  34.       window.scrollTo(0, selected.offset().top);
  35.     }
  36.     return;
  37.   }
  38. });

As you can see, it is important to leave the input and textarea fields alone, so the keyboard shortcuts don’t interfere with the user typing some text. With a little bit of CSS the selected comment can be displayed with a different border color or background. And that’s it!

Check an example topic at www.spaniards.es

2 responses so far