Search code examples
jqueryhtmlkeypress

jQuery keypress duplicate


I'm trying to display what an user has typed using jQuery to detected pressed keys.

For example, if the users presses "a" then "a" is displayed. When they then press "z", then "az" is displayed, and so on.

My code:

<script>
    $(document).ready(function() {
        var res = "";

        $("*").keypress(function( event ) {
            res = res + String.fromCharCode(event.which);
            $("#go2").html(res);
        });
    });
</script>


<p id="go2"></p>

Displaying String.fromCharCode(event.which) instead of res correctly shows the pressed keys, however the current code duplicates the keys.

When I press "a" then "aaa" is displayed. Pressing a new key like "z" then shows "aaazzz". Why are the keys being duplicated?


Solution

  • The problem is in your * selector, which gets applied to both <body> and <html>.

    Simply increasing the specificity to body will cause your duplication to disappear:

    $(document).ready(function() {
      var res = "";
      $("body").keypress(function(event) {
        res = res + String.fromCharCode(event.which);
        $("#go2").html(res);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="go2"></p>