Thursday, April 30, 2009

event.keycode problem Firefox

Solution for event.keycode problem for Firefox and Chrome


I was trying to identify which key is pressed by user  so that I can perform operation accordingly.  keyup event works perfectly with IE, but it was not behaving as expected for Firefox and Chrome.

Following is solution i came across to solve event.keycode problem for firefox (Fix to identify which key is pressed by user on IE, Firefox and Chrome)

function WhichKeyPress(e) {
 if (!e) {
  //if the browser did not pass the event 
  //information to the function, 
  //we will have to obtain it from the 
  //event register
  if (window.event) {
       //Internet Explorer
        e = window.event;
     } else {
       //total failure, we have no 
      //way of referencing the event
       return;
     }
   }
   if (typeof (e.keyCode) == 'number') {
      //DOM
      e = e.keyCode;
    } else if (typeof (e.which) == 'number') {
      //NS 4 compatible
      e = e.which;
    } else if (typeof (e.charCode) == 'number') {
     //also NS 6+, Mozilla 0.9+
      e = e.charCode;
    } else {
      //total failure, we have no way of obtaining the key code
      return;
    }
}

I have called the above function in following manner.
<body onkeyup="WhichKeyPress();">

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape