About

Labels

slider

Recent

Navigation

Add keyboard functions to website using jQuery


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.
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: