-1

I notice that Javascript code seems to be written to read keystrokes in completely different ways, which I guess is to support different browsers. For example, here is one code block from a web page:

if (document.addEventListener)
{
   document.addEventListener("keydown",keydown,false);
   document.addEventListener("keypress",keypress,false);
   document.addEventListener("keyup",keyup,false);
   document.addEventListener("textInput",textinput,false);
}
else if (document.attachEvent)
{
   document.attachEvent("onkeydown", keydown);
   document.attachEvent("onkeypress", keypress);
   document.attachEvent("onkeyup", keyup);
   document.attachEvent("ontextInput", textinput);
}
else
{
   document.onkeydown= keydown;
   document.onkeypress= keypress;
   document.onkeyup= keyup;
   document.ontextinput= textinput;   // probably doesn't work
}

Judging from this code it would appear different browsers have completely different keystroke handling mechanisms. Which of the above mechanisms corresponds to which browser(s)?

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • Read MDN: [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – epascarello Mar 22 '16 at 17:04
  • The events you list there in the code are not identical at all, they got different purposes: http://stackoverflow.com/questions/3396754/onkeypress-vs-onkeyup-and-onkeydown – Jonast92 Mar 22 '16 at 17:09
  • http://quirksmode.org/js/introevents.html. Basically, all non-archaic browsers do support the standard `addEventListener` these days. – Bergi Mar 22 '16 at 17:13

1 Answers1

1

addEventListener is supported by:

  • All modern browsers (including Microsoft Edge, and IE9-IE11 when not in their broken "compatibility" mode)
  • Nearly all old browsers that aren't from Microsoft

attachEvent is supported only by older browsers from Microsoft (or IE9-IE11 when in the broken "compatibility" mode).

The document.onkeydown = style hasn't been needed anytime this century, that was a seriously old mechanism (which still works) from before IE5.5.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875