1. Home
  2. WordPress
  3. How to add Keyboard Navigation to your WordPress powered website

How to add Keyboard Navigation to your WordPress powered website

Keyboard navigation make visitors experience at websites more easy and faster. I saw few websites with Keyboard navigation and found it was quickest and thought to implement it on my website too. Below i will be showing you how you also could implement it on your website powered by WordPress.

How to Add Keyboard Navigation to your WordPress powered website
How to Add Keyboard Navigation to your WordPress powered website

Open the single.post.template.html file under theme template folder and add the below code after the content.

<div class="prev" style="display:none;">
              <?php previous_post_link('%link', 'Previous'); ?>
</div>
<div class="next" style="display:none;">
              <?php next_post_link('%link', 'Next'); ?>
</div>

Step 2 : Using native keydown() method of jQuery

Using jQuery, bind the key-down event to a function that extracts the required URL from one of these above created hidden links and injects it into the browser’s address bar, loading the new page. On key-down, check whether the key pressed is right arrow (39) or left arrow (37), extract the corresponding required URL from above created hidden links and load the new URL. Add the below code to the same single.post.template.html file after the above Step 1 code is inserted :

<script type="text/javascript">
jQuery(document).ready(function () {
 
    jQuery(document).keydown(function(e) {
        var url = false;
        if (e.which == 37) {  // Left arrow key code
            url = jQuery('.prev a').attr('href');
        }
        else if (e.which == 39) {  // Right arrow key code
            url = jQuery('.next a').attr('href');
        }
        if (url) {
            window.location = url;
        }
    });
 });
</script>

Go ahead, try it. Hit the left-arrow ← to view the previous post and right-arrow → to view the next post. You’ll be amazed at just how quickly you can navigate through the posts.

Updated on September 2, 2017

Was this article helpful?

Related Articles

Add A Comment