Animation div with Jquery does not recognize keys

Asked

Viewed 68 times

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){
                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>
  </body>
</html>

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

1 answer

5

Change the event of keyPress for keyDown that works perfectly:

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

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

As says the jquery documentation:

This is similar to the keydown Event, except that Modifier and non-printing Keys such as Shift, Esc, and delete Trigger keydown 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>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

Like the arrow doesn’t print of no char, she is not recognized in keypress.

  • ball show man, thank you !

  • Why not keypress?

  • @Rafaelmafra, edited by :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.