Student
Student

Reputation: 28345

Trying to understand javascript's key event handling

I would like to know why this page's source use all this if-else to add an event listener:

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
}

Is it to be compatible with most browsers?

Upvotes: 2

Views: 382

Answers (1)

Anurag
Anurag

Reputation: 141879

if (document.addEventListener) // DOM spec that all browsers should follow

else if (document.attachEvent) // but unfortunately IE does not follow them    

else // and there may be other older browsers that follow neither

Upvotes: 1

Related Questions