Search code examples
javascriptkeyboardwebkitdom-eventskeypress

Firing a keyboard event, webkit keyboard event doesn't fire


I have JavaScript code that listens to the "return" key pressed,
works on all browsers except webkit browsers.

I am aware of webkits recent changes to keyboard event handling.
I cant find the right solution in this detailed explanation.

Here is the code:

function addEventHandler(node,type,fn){
   if(typeof window.event !== "undefined"){
            /* Internet Explorer way */
            node.attachEvent( "on" + type, fn );
   } else {
           /* FF & Other Browsers */
           node.addEventListener( type, fn,false );
   }
} 


function detectSubmit(){
    searchTextInput = document.getElementById("txtSearch")
    addEventHandler(searchTextInput,"keydown",triggerSearch);
}

function triggerSearch(e){
  //getting the character that was pressed cross browser. 
     var key = e.keycode ? e.keycode : e.which;
  //detect if the return key was pressed. 
    if(key==13){
      alert("return clicked");
    }
}

   addEventHandler(window,"load",detectSubmit);

Solution

  • The most obvious thing is the simple typo on the following line:

    var key = e.keycode ? e.keycode : e.which;
    

    It should be keyCode rather than keycode.

    Other than that, there are problems in the addEventHandler function. I suggest the following:

    function addEventHandler(node,type,fn){
        if (typeof node.addEventListener !== "undefined"){
            /* DOM-compliant method */
            node.addEventListener( type, fn,false );
        } else if (typeof node.attachEvent !== "undefined") {
            /* IE */
            node.attachEvent( "on" + type, fn );
        }
    }
    

    Two things: first, it's better to check for attachEvent directly rather than infer its existence from the existence of window.event. In fact, window.event exists in Safari and Chrome but not (I think) attachEvent, so that dodgy inference is preventing your code from working.

    Secondly, it's better to check for the DOM standard addEventListener first and use it where it exists rather than attachEvent. Opera, for example, has both but only addEventListener is standardised.