Blogger Ever

Add keyboard functions to website using jQuery

Keyboard shortcuts or navigation make your site more user friendly and let the user be more convenient with your site.

Last time while redesigning the blog, I received an email from a young JS enthusiast telling to add keyboard press function to scroll across posts. I found it pretty interested because Google and Facebook also have key press function so why not this blog. I added J,K and L key buttons to navigate through out the site.


There could more be done like bookmarking the site, save the content for later reading or to share something with real ease. Endless possibilities and countless coding can be done with this function.

Basically jQuery have 3 Keyboard events, keyup, keydown and keypress. keypress and keydown are identical, except keypress doesn't recognize shift, alt, ctrl keys.So I prefer to use keydown function for your stuff.

Lets create our function when a user presses a key.
 $(document).bind('keydown', function (e) {
// Do stuff right here
});
Since any keyboard event works on text input stuff, so first we shall bind it to DOM. Once its done, next step is to detect the key which is pressed. We have passed an argument, this holds the info about the key pressed. Using .which property we can recognize the key pressed,
var keyx=(e.which==88) ? true : false;
Now let see that pressed key is either 'x' or not.
$(document).bind('keydown',function(e){
  var keyx=(e.which==88) ? true : false;
  if(keyx){
    alert('Key X presssed');
  }
});
Now above function alerts when a person presses X. This post includes a starter of keyboard stuff with a web. Email me if you want something specific.
Blogger

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.