/    Sign up×
Community /Pin to ProfileBookmark

capturing keyboard input

Is there any way to capture keyboard input from an entire page? Neither the Document nor the Window objects have an onkeypress event handler. I need something like an onkeypress for the entire page. For example, even if an input element has the input focus, I don’t necessarily want the typed text to show up in the element. I need all keyboard input to go through one function first. Does anyone have an idea as to what would be the best way to do this? Setting document.onkeypress to a function when the page loads does work on some browsers, but not all, and it is not standard.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@scragarSep 14.2008 — if (window.addEventListener)
window.addEventListener('keydown', myKeyDown, false);// good browsers
if(document.body && document.body.attachEvent)
document.body.attachEvent('onkeydown' myKeyDown);// IE

function myKeyDown(e){
var ev = e||event;
var key = ev.which||ev.keyCode;
var char = String.fromCharCode(key);

alert('KeyCode: '+key+"nCharacter: "+char);
};

because of bubling though it's impossible to grab it from the window before the object.
Copy linkTweet thisAlerts:
@Logic_AliSep 14.2008 —  if an input element has the input focus, I don't necessarily want the typed text to show up in the element. I need all keyboard input to go through one function first. [/QUOTE]You could make the relevant inputs uniquely identifiable if necessary, then use a loop to assign them your filtering function as a key event handler.
Copy linkTweet thisAlerts:
@DokSep 14.2008 — because of bubling though it's impossible to grab it from the window before the object.[/QUOTE]If you want to use the capture phase instead you can get support for IE here.
×

Success!

Help @sawatdee spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...