Yesterday, I added hotkey navigation feature on SumTips. Now you can quickly move between posts without using your mouse. To read the previous post, you just have to press
Adding Keyboard Shortcut Navigation on WordPress
So how did I add it? Along with a small code snippet (coming up), all that was required was WordPress and jQuery. Since these were already used here, adding this feature felt quite obvious as it would help users.
If you scroll down this page, you will find the WordPress navigation links for next and previous posts. Using jQuery, we can bind the keyboard’s keydown event to a function that extracts any of these navigation page’s URL and inject it automatically into the browser’s address bar. I chose native jQuery method here, however there’s also a great plugin called jQuery.hotKeys that could be used. This plugin has many benefits over the native method, but more on it later.
Here’s the navigation URL markup:
<div class="navigation navigation-single"> <div class="alignleft"> <div class="nav-previous"><?php next_post_link( '%link', '%title'); ?></div> </div> <div class="clearfix"></div> </div> <div class="navigation navigation-single"> <div class="alignright"> <div class="nav-next"><?php previous_post_link('%link', '%title'); ?></div> </div> <div class="clearfix"></div> </div>
And here’s the jQuery code:
$(document).ready(function () { $(document).keydown(function(event) { var url = false; if (event.which == 74 || event.which == 37) { url = $('.nav-previous a').attr('href'); } if (event.which == 75 || event.which == 39) { url = $('.nav-next a').attr('href'); } if (url) { window.location = url; } }); });
I am using two keys, hence the multiple conditions for each action. If you want to use just the left-right keys, remove 74 & 75 key check.
By using the plugin you could achieve the same behavior using this code:
$(document).ready(function () { $(document).bind('keydown', 'left', function() { var url = $('.nav-previous a').attr('href'); if (url) { window.location = url; } }); $(document).bind('keydown', 'right', function() { var url = $('.nav-next a').attr('href'); if (url) { window.location = url; } }); });
We are only checking for left/right keydown here.
Benefits of using jQuery.hotKeys:
- With the plugin you can use almost any keyboard combination in your code. For example,
Ctrl +A :
$(document).bind('keydown', 'ctrl+a', fn);
- Shortcut doesn’t fire when a user is typing into a text field – without the plugin your site visitors may face trouble while commenting or performing search.
- Supports ‘keydown’, ‘keyup’ and ‘keypress’
- Plugin works with jQuery 1.4.2+
- Compatible with almost all browsers