Remap a key press in javascript / jquery
Is there an "easy" way to map a keystroke to another key when on a page?
Background:
We are using a custom javascript grid for handling ke开发者_开发知识库yboard entry in a web application. Normally, the [enter] key allows the user to move to the next line, and the [tab] key allows the users to move to the right. The grid handles the keystrokes, and has some rather complicated logic when one is pressed.
Our users are requesting that we map the Plus Key [+] on the numeric keypad to [tab] so that they don't need to use two hands while keying. This seems logical (the are keying thousands of numbers in a row while holding papers with their other hand), but I can't figure out to do it.
Well you could do something like this:
$(document).keydown(function(e){
if(e.keyCode == 107) { // + key on num keyboard on my keyboard, test your clients to be sure
e.preventDefault();
//trigger tab functionality here
}
});
To trigger the tab functionality, i'd use focus()
called on elements which have tabindex="0"
set so they fall into the natural taborder of the page and are focusable - if it is formelements they are already focusable and there is no need for the tabindex attribute.
You can trigger a keypress event on an element when the +
or -
keys are press on an element by doing this:
$("body").keypress(function(e){
if ( e.which === 43 || e.which === 45 ) {
$(e.target).trigger({
type: "keypress",
which: 13
});
e.preventDefault();
}
});
This triggers the enter key on both -
and +
. You should be able to trigger the tab event too, however it will not cause the default browser behavior of going to the next element.
精彩评论