onKeyPress event not working in Firefox

此生再无相见时 提交于 2019-11-27 09:06:35

When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers.

To catch all different keypress() apis, like the link from Emmett shows, can be very difficult.

Example:

In HTML head:

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

In the JS tag:

$(document).keydown(function(event) {
 alert('You pressed '+event.keyCode);
 event.preventDefault();
});

Browsers have different ways of handling keyboard events. Have a look at http://unixpapa.com/js/key.html for more info.

For example, these changes to your code will get it working in Firefox:

<body bgcolor="lightblue" onkeypress="keypress(e)">

and

function keypress(e) {
    alert(window.event ? event.keyCode : e.which);
    // other stuff
}
Kumar

Pass event object as an parameter and your code will work in IE as well as firefox. The code example is as follows :

<body bgcolor="lightblue" onkeypress="keypress(event)">
function keypress(event) {
  alert(event.keyCode);
  var key=event.keyCode;
  if(key==112 || key==80)
      printDiv();
  else if(key==101 || key==69)
      window.location="http://google.com";
  else if(key==114 || key==82)
      window.reset();  
}

I think Firefox are not caring programmers... and this is the reason why so, In Firefox navigator.appName returns "Netscape". so user can edit his code like,

if(navigator.appName == "Netscape") 
    Key = event.charCode; //or e.which; (standard method)
else 
    Key = event.keyCode;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!