Site icon SumTips

Adding Hotkey Navigation Feature on WordPress Posts

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 j or left arrow key, and to move ahead to the next post, press k or right arrow key. If you are a Google addict, you will find the j and k keys particularly comfortable to use.

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:

$(document).bind('keydown', 'ctrl+a', fn);
Exit mobile version