Nathan Gilford Nathan Gilford - 1 year ago 71
Javascript Question

JS/JQuery on keypress proper usage

I'm working on creating a more accessible navigation, and in particular want to use determine whether a keypress is used. While I want to figure out why this is not working for me, I also want to know the difference between several methods that do the same thing. Those methods are:

$('ul li a').on('keypress', function(e){...});

$('ul li a').keypress(function(e) {...});

$('ul li a').bind('keypress', function(e) {...});

What is the difference if any? And is there a 'right' one to use for this siutation? Either way, none of them are actually working for me. I have setup console logs throughout the script I have written and while the console is logging the script loading, it detects the keydown, however it does not detect the return key being pressed, the whole script looks like:

$('ul li a').on('keypress', function(e){
if(e.keyCode==13){ // return / enter key
console.log("Return Key Pressed");
return false;


** EDIT **

I never discovered why the return key (or down arrow) was not working, neither would trigger the keydown event in the console, but I did discover the spacebar is the best method for accessibility, the end result looked like:

$('ul li a').on('keypress', function(e){
if ((e.keyCode || e.which) == 32) { // spacebar
... script ...
return false;

Answer Source
  • Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.

    However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

If you look in the source code for $.fn.bind you will find that it's just an rewrite function for on:

function (types, data, fn) {
    return this.on(types, null, data, fn);
  • For keypress function, i don't recommend it because it work only for exsiting elements ; if element will be exist after running keypress , it will not handle new elements.

    Instead you can use delegate :

    $(document).delegate('ul li a','keypress',function(event){