Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

action by key press

I'm designing a web based accounting software. I would like to open the "new accounting document" whenever the user press N key for example. And open "settings" whenever he/she is pressing S key.

I saw some scripts based on JavaScript and jQuery. But they did not work exactly. Can anyone help me please ?

I have tried this script:

var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
   //Do something
}
like image 870
Mohammad Saberi Avatar asked Nov 28 '11 11:11

Mohammad Saberi


2 Answers

$(document).bind('keyup', function(e){
    if(e.which==78) {
      // "n"
    }
    if(e.which==83) {
      // "s"
    }
});

To prevent if an input is focused:

$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ $(document).bind('keyup', function(e){ etc.... });

You might want to put the bind function into its own function so you don't duplicate code. e.g:

function bindKeyup(){
    $(document).bind('keyup', function(e){
      if(e.which==78) {
        // "n"
      }
      if(e.which==83) {
        // "s"
      }
    });
}
$("body").on("focus",":input", function(){ $(document).unbind('keyup'); });
$("body").on("blur",":input", function(){ bindKeyup(); });
like image 57
Thomas Clayson Avatar answered Oct 19 '22 19:10

Thomas Clayson


You can detech keypresses in jQuery using either .keypress() or .keyup() methods, here is a quick example :

$(document).keyup(function(event) { // the event variable contains the key pressed
 if(event.which == 78) { // N keycode
   //Do something
 }
});

Here is a list of keycodes : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Update 1

.keyup and .keydown have different affects - as per comments from @ThomasClayson -: keyup is the best one to go for as keypress will repeat if the key is held down. it registers an event for each character inserted. It also doesn't register modifier keys such as shift (although not necessary here, it might be something to keep in mind)

Update 2

This is from the jQuery keyup doc site :

To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows.

Affectively meaning that which.event is all you need to determine which key has been used. Thanks @nnnnnn

like image 3
Manse Avatar answered Oct 19 '22 21:10

Manse