Skip to content

Instantly share code, notes, and snippets.

@letsgetrandy
Created March 21, 2013 19:37
Show Gist options
  • Save letsgetrandy/5216017 to your computer and use it in GitHub Desktop.
Save letsgetrandy/5216017 to your computer and use it in GitHub Desktop.
Wordpress plugin to enable J/K keys for navigating posts.
jQuery(function() {
if (jQuery('.post').length < 2) return;
jQuery(document).keypress(function(e) {
var f=false, b=false;
if (e.target.tagName.match(/input|textarea/i)) return;
switch (e.which) {
case 75:
case 107:
b=true;
break;
case 74:
case 106:
f=true;
break;
}
if (!f && !b) return;
jQuery('.post').each( function(i,el) {
if(f && parseInt(jQuery(el).offset().top,10) > parseInt(jQuery(document).scrollTop(),10)) {
if(jQuery(document).scrollTop() + jQuery(window).height() >= jQuery(document).height()){
pnkeynavPage(1);
}
jQuery(document).scrollTop(jQuery(el).offset().top);
f = false;
}
if(b && parseInt(jQuery(el).offset().top,10) >= parseInt(jQuery(document).scrollTop(),10)) {
var d=jQuery('.post').get(i-1);
if (i > 0) {
jQuery(document).scrollTop(jQuery(d).offset().top);
b = false;
} else {
pnkeynavPage(-1);
}
}
});
if (f) {
pnkeynavPage(1);
}
});
});
function pnkeynavPage (inc) {
var path = window.location.pathname;
if (p=path.match(/\/page\/(\d+)\/?$/)) {
var p = parseInt(p[1], 10) + inc;
var s = p > 1 ? '/page/'+p+'/' : '';
window.location.pathname = path.replace(/\/page\/(\d+)\/?$/, s);
} else if (inc > 0)
window.location.pathname = path + '/page/2/';
}
<?php
/*
Plugin Name: Prev-Next Keyboard Navigation
Description: Prev-Next navigation of posts with the J/K keys
Author: Randy Hunt
Version: 0.6
Author URI: http://www.bbqiguana.com/
*/
$keynavCount = 0;
if (!is_admin()) {
$pnkeynavdir = trailingslashit(get_bloginfo('wpurl')).PLUGINDIR.'/'.dirname(plugin_basename(__FILE__));
wp_enqueue_script("jquery");
wp_enqueue_script("pnkeynav", $pnkeynavdir.'/pnkeynav.js', array('jquery'));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment