Search code examples
javascriptdom-events

Event in Firefox "e is undefined"


I have a function that get the key code when pressed.

Here is my code:

function Getkeycode(e){
   var keycode = null;
   if (window.event) 
       keycode = window.event.keyCode;
   else 
       keycode = e.which;
   return keycode;
}

window.onkeydown = function(){
   alert(Getkeycode());  // I'm tried to using  Getkeycode() or Getkeycode(e) but still error
}

Previous code works well in Internet Explorer, but in Firefox always occurs error message >> e is undefined or e is not defined


Solution

  • In IE, when an event occurs it is globally accessible in a window variable. That's not the case in other browsers.

    In order to pass the event to your function, change your code to

    window.onkeydown = function(e){ // <== receive e
       alert(Getkeycode(e));  // <== pass e
    }