Skip to content

Instantly share code, notes, and snippets.

@nauzilus
Created May 27, 2015 23:02
Show Gist options
  • Save nauzilus/c57bc1d4d7240ed3c5c2 to your computer and use it in GitHub Desktop.
Save nauzilus/c57bc1d4d7240ed3c5c2 to your computer and use it in GitHub Desktop.
Simple Keyboard Navigation
(function(selector) {
// not handling DOM changes. yet.
var posts = document.querySelectorAll(selector);
var topTollerance = 10;
var multiplier = 0;
function post_nav(e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;
var dir = 0;
var key = (""+(e.keyCode || e.code || e.key || "")).toLowerCase();
switch(key) {
// don't hijack arrow keys. that's so fucking annoying
// use vim direction keys
case "keyl":case "l":
case "keyj":case "j":
dir = 1;
break;
case "keyk":case "k":
case "keyh":case "h":
dir = -1;
break;
}
if ( dir ) {
dir *= (multiplier || 1);
multiplier = 0;
var next = [].slice.call(posts).map(function(v,i) {
return v.getBoundingClientRect().top <= topTollerance ? null : i;
}).filter(function(v) {
return v != null;
})[0];
if (next === undefined) {
next = posts.length;
}
var current = next - 1;
current += dir;
current = Math.max(Math.min(posts.length-1, current), 0);
posts[current].scrollIntoView();
e.preventDefault();
}
else if (multiplier < posts.length) {
var num = Number((key.match("(?:numpad|digit)([0-9])")||[])[1]);
if (!isNaN(num)) {
if (multiplier) {
multiplier *= 10;
}
multiplier += num;
}
}
}
document.addEventListener("keypress", post_nav);
})("h2");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment