How to register document.onkeypress event
Solution 1
You are looking for:
EDIT:
Javascript:
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("You hit the enter key.");
} else {
alert("Oh no you didn't.");
}
}
DEMO: JSFIDDLE
Solution 2
You are probably looking for:
document.body.addEventListener('keydown', function (e) {
alert('hello world');
});
But it is almost certainly going to be worth your time to use an existing library to abstract over the problems of the many browsers out there.
Related videos on Youtube
![Nilesh Pethani](https://i.stack.imgur.com/BziJ9.jpg?s=256&g=1)
Nilesh Pethani
I am technology lead at Interview Mocha (Insaas Software PVT LTD). By heart I am DEVELOPER. I work with Microsoft technologies like ASP.NET MVC, C#, MS SQL. I also work in cloud development. Interview Mocha is pre employment online testing solution. Interview Mocha provide a wide range of pre built skills test to perform first level screening of candidate. We have excellent set of tools and simulators to validate the candidate's skills.
Updated on July 09, 2022Comments
-
Nilesh Pethani almost 2 years
I want to register keypress events for a document using javascript.
I have used:
document.attachEvent("onkeydown", my_onkeydown_handler);
It works fine with IE, but not with Firefox and Chrome.
I also tried:
document.addEventListener("onkeydown", my_onkeydown_handler, true); // (with false value also)
But it still doesn't work with Firefox and Chrome.
Is there a solution, am I missing something?
-
UltraInstinct almost 12 years
-
-
Nilesh Pethani almost 12 yearsi want to add event to document itself
-
multitask landscape over 5 yearsWhat problems? Why do you then give the solution which can't be used in real application?
-
Lucas Green about 5 years@AndriiNemchenko because the solution which can be used in a real application is built from this, and has already dealt with the problems. I can't evaluate what library they should use, but I can show them something they could use to build the solution and warn them it is hard.