Monday, October 15, 2012

Handling cross-browser key events with jQuery

Another little copy-paste code fragment from the house of jQuery :) If you need to od different things on keydown event, use this basic structure, so it will be cross-browser friendly:



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
jQuery(document).keydown(function (e) {

 var evt=(e)?e:(window.event)?window.event:null;
 if(evt){
  var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
  
  // the key specific code comes here:
  console.log(key);

 }

}); 


I've tested it on Chrome, FF and IE9-10, and it works well.