5

I am trying to make a console like application, so I am catching all the keypress on the window and do related stuff with them(not important). Problem is at backspace. I have the following code:

$(window).bind("keypress",function(e){
        var code = e.keyCode || e.which;
        if ( code == 8) {
            a = $("#console").html();
            $("#console").html(a.substring(0,a.length-1));
            currentCommand = currentCommand.substring(0,currentCommand.length-1);           
            e.preventDefault();
        }

However, in Firefox, contents of the #console is deleted but Chrome does not execute the code above. I need a cross-browser compatible solution. What am I missing?

ADDITION:

If I use keydown/keyup instead of keypress, I am unable to detect if the characeter was 'A' or 'a' it always returns 'A'.

Mustafa
  • 10,013
  • 10
  • 70
  • 116
  • Possible duplicate of [Javascript e.keyCode doesn't catch Backspace/Del in IE](http://stackoverflow.com/questions/4084715/javascript-e-keycode-doesnt-catch-backspace-del-in-ie) –  Apr 14 '16 at 05:52
  • Yes, not an exact duplicate, but the question is answered there. –  Apr 14 '16 at 05:53

1 Answers1

4

Read this. IE doesn't fire keypress for those special keys. Perhaps it's the same with some of the other browsers.

Javascript e.keyCode doesn't catch Backspace/Del in IE

Community
  • 1
  • 1
Tys
  • 3,592
  • 9
  • 49
  • 71
  • if i make: `$(window).bind("keydown",function(e){ var code = e.keyCode || e.which; console.log(code);` It always gets me caps characters such as it is alwayws 65 whether I press A or a – Mustafa Dec 19 '11 at 23:59
  • Perhaps you can try to see whether the SHIFT button was pressed? Like explained in this thread: http://stackoverflow.com/questions/3125727/how-to-differeniate-capital-letters-from-lower-ones-in-onkeydown-event-handler-m – Tys Dec 20 '11 at 12:12
  • No, I'M sure SHIFT was not pressed – Mustafa Dec 20 '11 at 17:08