notes.husk.org. scribblings by Paul Mison.

2009-03-10

Keyboard Navigation In Tumblr

text 17:23:00

For a while, I’ve had a small bit of JavaScript into the templates of notes.husk.org that enables vi/ffffound/Google Reader style navigation with the j and k keys. Hit ‘j’ and the page will scroll to the next entry; ‘k’ and it will move to the previous one. It even handles paging (well, paging with j, anyway).

It’s not very complicated code, and (unlike the code at ffffound) it doesn’t handle scrolling by the user (as opposed to itself) nicely; nor does it handle going backwards very well. Nonetheless, it’s better than nothing, and it’s surprisingly easy to add. So, here’s the code. (Note that you’ll want each of your divs to have the ‘tumblr’ class, or you’ll want to change the code to match your HTML.)

        var posts = $("div.tumblr"), idx = -1;
        $(document).keypress(function (e) {
          if (e.which != 106 && e.which != 107) {
            return;
          }
          if (e.which == 106) {
            if (idx < posts.length - 1) {
              idx++;
            } else {
              // find link to older page
              link = $('ul.nav li a:contains(older)').attr('href')
              if (link) {
                if (!link.match(/^http:/)) {
                  link = 'http://'+window.location.host+link;
                }
                location.href = link;
              }
            }
          }
          if (e.which == 107) {
            if (idx > 0) {
              idx--;
            } else {
              // find link to older page
              link = $('ul.nav li a:contains(newer)').attr('href')
              if (link) {
                if (!link.match(/^http:/)) {
                  link = 'http://'+window.location.host+link;
                }
                location.href = link;
              }
            }
          }
          var top = $(posts[idx]).offset().top+1;
          window.scrollTo(0, top);        

(This was posted somewhat as a response to Aza Raskin’s post about keyboard navigation and implementing it with Greasemonkey. However, I agree with the commenters: ffffound sets the bar for this (and my code is, as I’ve said, nowhere near as good), and I find the scrolling jarring. I think I also prefer the use of j/k not the arrow keys, because users have expectations of the latter.)

about

posts

tags

notes

  1. blech posted this

options