171

I'm using a keypress listener eg..

addEventListener("keypress", function(event){

}

However, this doesn't seem to detect a backspace which erases text...

Is there a different listener I can use to detect this?

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Skizit
  • 43,506
  • 91
  • 209
  • 269

8 Answers8

197

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35
85

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • I haven't looked into the standards, but the event order (in Firefox 37 at least) seems to be `keydown` `keypress` `keyup`. http://unixpapa.com/js/testkey.html – jxmallett Apr 14 '15 at 23:36
  • 1
    It also seems that, for key events in inputs, the character doesn't appear in the field until the `keyup` event is fired. – jxmallett Apr 15 '15 at 00:13
  • Last one - On iOS (8.2) the backspace key only fires a `keydown` event but the character isn't removed from the input until sometime after that. – jxmallett Apr 15 '15 at 00:24
  • this is the answer. this captures delete key press and Ctrl+V keypress – user1709076 May 26 '17 at 04:11
33

The keypress event might be different across browsers.

I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress event will be triggered or not -- backspace will trigger keydown/keypress/keyup on Firefox but only keydown/keyup on Chrome.

Single keyclick events triggered

on Chrome

  • keydown/keypress/keyup when browser registers a keyboard input (keypress is fired)

  • keydown/keyup if no keyboard input (tested with alt, shift, backspace, arrow keys)

  • keydown only for tab?

on Firefox

  • keydown/keypress/keyup when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress is fired even with no input)

  • keydown/keyup for alt, shift


This shouldn't be surprising because according to https://api.jquery.com/keypress/:

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)

The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.


Finally, to answer your question, you should use keyup or keydown to detect a backspace across Firefox and Chrome.


Try it out on here:

$(".inputTxt").bind("keypress keyup keydown", function (event) {
    var evtType = event.type;
    var eWhich = event.which;
    var echarCode = event.charCode;
    var ekeyCode = event.keyCode;

    switch (evtType) {
        case 'keypress':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        case 'keyup':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");
            break;
        case 'keydown':
            $("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
            break;
        default:
            break;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="inputTxt" type="text" />
<div id="log"></div>
user2314737
  • 27,088
  • 20
  • 102
  • 114
20

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
13

event.key === "Backspace"

More recent and much cleaner: use event.key. No more arbitrary number codes!

note.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace") {
        // Do something
    }
});

Mozilla Docs

Supported Browsers

Community
  • 1
  • 1
Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • 1
    In 2018 this is the best way to go about this! – tfantina Jun 29 '18 at 21:49
  • I've been using key code 8 for backspace in every single language I worked with. Learn the ASCII codes, they're not arbitrary. – André Werlang Jul 27 '18 at 22:37
  • 4
    Just because you *have* been using doesn't mean there isn't a better option. `.key` is currently the recommended option by the docs. In addition, it supports various international keyboards with different mappings for any given key. They aren't *arbitrary* in the sense that they are fixed, but they are when reading code – Gibolt Jul 27 '18 at 23:59
9

My numeric control:

function CheckNumeric(event) {
    var _key = (window.Event) ? event.which : event.keyCode;
    if (_key > 95 && _key < 106) {
        return true;
    }
    else if (_key > 47 && _key < 58) {
        return true;
    }
    else {
        return false;
    }
}

<input type="text" onkeydown="return CheckNumerick(event);" />

try it

BackSpace key code is 8

VolkanCetinkaya
  • 645
  • 7
  • 13
3

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

arash nadali
  • 568
  • 4
  • 7
0

I was trying keydown and Backspace was not being captured. Switching to keyup worked for me.

addEventListener("keyup", function(event){

}

For reference, in case someone is using with .on for dynamically generated content.

$("body").on( "keyup", ".my-element", function(evt) {
      // Do something
});
Shahbaz A.
  • 4,047
  • 4
  • 34
  • 55