Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript keycode clash: "right arrow" and "single quote"

The following script does what it should, that is, it reacts on the keys "arrow left" and "arrow right". However, due to a keycode clash, it reacts on a single quote as well. It makes it impossible to enter that character into an input field. Can anything be done about that?

<script type="text/javascript">
  onload = function(){
    document.onkeypress=function(e){
      if(window.event) e=window.event;
      var keycode=(e.keyCode)?e.keyCode:e.which;

      switch(keycode){
        case 37: window.location.href='set.jsp?index=5';
          break;
        case 39: window.location.href='set.jsp?index=7';
          break;
      }
    }
  }
</script>
like image 747
arataj Avatar asked Sep 24 '26 18:09

arataj


2 Answers

When the user presses the single quote key, the e.keyCode property is zero, and the e.which property is 39. Executing String.fromCharCode(39) returns a single quote.

You want the keyCode if that property is in the event object:

var keycode = "keyCode" in e ? e.keyCode : e.which;

That way you get zero for the keyCode when that property exists in the event object, and when the which property also exists.

document.onkeydown = function(event) {
    event = event || window.event;

    var keyCode = "keyCode" in event ? event.keyCode : event.which;

    switch (keyCode) {
        case 37: console.log("37 was pressed", event); break;
        case 39: console.log("39 was pressed", event); break;
    }
};

Edit #1: Other commenters and answers are correct. I forgot you shouldn't be detecting control keys with keypress events. Changed to onkeydown.

Full HTML example that works cross browser:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>Key Codes Test</title>
</head>
<body>
    <script type="text/javascript">
        document.onkeydown = function(event) {
            event = event || window.event;

            var keyCode = "keyCode" in event ? event.keyCode : event.which;

            switch (keyCode) {
                case 37: console.log("37 was pressed", event); break;
                case 39: console.log("39 was pressed", event); break;
            }
        };
    </script>
    <input type="text" size="30">
</body>
</html>
like image 72
Greg Burghardt Avatar answered Sep 26 '26 06:09

Greg Burghardt


keypress should not capture control keys like left/right arrow. if you use keydown event, single quote keycode is 222 definitely no conflict

like image 26
hjl Avatar answered Sep 26 '26 07:09

hjl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!