Animation div with Jquery does not recognize keys

6
<!DOCTYPE html>
<html lang="pt">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <title></title>    

    </style>

  </head>
  <body>
    <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script>$(document).ready(function(){$(document).keypress(function(x){if(x.wich==13||x.keyCode==13){vardiv=$("div");
                div.animate({height: '300px', opacity: '0.4'}, "slow");
                div.animate({width: '300px', opacity: '0.8'}, "slow");
                div.animate({height: '100px', opacity: '0.4'}, "slow");
                div.animate({width: '100px', opacity: '0.8'}, "slow");
            }
          });
        });

    </script>
  </body>
</html>

Personal, this code is only working with key enter (keycode 13). If I change to another key, like 39 for example, and press, it does not perform the action.

    
asked by anonymous 31.12.2016 / 19:57

1 answer

5

Change the event from keyPress to keyDown that works perfectly:

Note: The right is x.which and not x.wich:

The basic difference is that keypress recognizes character insertion, or a change in input, similar to input event.

As the JQuery documentation says:

  

This is similar to the key event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger key events but not keypress events. Other differences between the two events may arise depending on platform and browser.

$(document).ready(function() {
  $(document).keydown(function(x) {
    if (x.which == 39 || x.keyCode == 39) { // right arrow
      var div = $("div");
      div.animate({
        height: '300px',
        opacity: '0.4'
      }, "slow");
      div.animate({
        width: '300px',
        opacity: '0.8'
      }, "slow");
      div.animate({
        height: '100px',
        opacity: '0.4'
      }, "slow");
      div.animate({
        width: '100px',
        opacity: '0.8'
      }, "slow");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><divstyle="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

As the arrow does not print char , it is not recognized in keypress .

    
31.12.2016 / 20:02