45

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?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Nilesh Pethani
  • 822
  • 2
  • 10
  • 19
  • [Possible answer here](http://stackoverflow.com/questions/3763080/javascript-add-events-cross-browser-function-implementation-use-attachevent-add) – UltraInstinct Aug 28 '12 at 05:43

3 Answers3

82

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

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
10

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.

Lucas Green
  • 3,951
  • 22
  • 27
  • 2
    @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. – Lucas Green Jun 18 '19 at 04:49
-4

Please go through following links for detailed description.

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener

http://www.reloco.com.ar/mozilla/compat.html

In short, write handler as

function myFunction(e)
{
    ///For IE
    if(!e)
        e=window.event;

    // use e as event in rest of code.
}
Kapil Sharma
  • 10,135
  • 8
  • 37
  • 66