Skip to content Skip to sidebar Skip to footer

How To Detect `delete` And `.` When User Press The Keyboard On Chrome?

When I press . it fires the three events, keydown, keypress and keyup. keydown which: 190 == ¾ keyCode: 190 == ¾ keypress which: 46 == . keyCode: 46 == . keyup which:

Solution 1:

I think the best solution would be to map the keys you want (demo), then use e.which to cross-reference what key was pressed. There is a good reference of cross-browser keyCode values, which work in this case because jQuery normalizes the e.which value.

var keys = {
  46  : 'del',
  190 : '.'
};

$("textarea").bind('keyup', function(e){
  $('#r').append( 'keyup (' + e.which + '): ' + (keys[e.which] || String.fromCharCode(e.which)) );
});

This is similar to the method that jQuery UI uses - see the keycodes cross-reference at the top of the file? And it is also the method I use in the keycaster plugin.

Solution 2:

In fact it's strange but it is logic.

The function String.fromCharCode is working with real char code, not with KB actions (left, delete...)

Why don't filter by keyCode simply ?

Solution 3:

I've forced the same behavior as Firefox, example on jsFiddle

$("textarea").keydown(function(e) {
    // if the key pressed was found on the list of specialCharsif (specialChars[e.keyCode])
    {
        // triggers the fake event
        $("textarea").trigger("chromekeypress", e);

        // temporary avoid keypress from firing
        $("textarea").unbind("keypress");
        setTimeout(function(){ $("textarea").bind("keypress", handleKey); },10);
    }
});

$("textarea").keypress(handleKey); // main event

$("textarea").bind("chromekeypress", chromeKeyPress); // chrome workaroundfunctionchromeKeyPress(i,e){
    e.type="chromekeypress";
    e.which = 0; // copy Firefox behavior, which == 0 means a special key pressedhandleKey(e); // fires the main event
}
functionhandleKey(e) {

    // which is going to be 0 if it is a special key// and keycode will have the code of the special key// or// which will have the value of the key

    $("#r").html($("#r").html() + "\n" +
        e.type + "\n" +
        "  which: " + e.which + " == " + String.fromCharCode(e.which) + "\n" +
        "  keyCode: " + e.keyCode + " == " + String.fromCharCode(e.keyCode) + "\n" +
     "");
}

Solution 4:

The value of "which" in a "keypress" handler does not have the same meaning as that of "which" in a "keydown" or "keyup" handler. In those, it's the keycode for the key on the keyboard, and not a character ordinal. In "keypress" it is the character, but you don't get a "keypress" for Del (as you've noticed).

Thus, that's a different 46 in the "keypress" handler (for ".") than in the "keydown" and "keyup" events for Del.

You probably should use either "keydown" or "keyup" and check for the keycode.

Post a Comment for "How To Detect `delete` And `.` When User Press The Keyboard On Chrome?"