Search code examples
javascriptjquerytextareakeypress

Prevent holding keyboard pressed in textarea


I need the user to insert text into a textarea as one letter per keypress, so if a key is held down it will write just one letter ('a') instead of multiple letters ('aaaaaaaaaaaaaaaaaaa'). To enter this last string the user must press-release the keyboard button multiple times.

Is this possible?

Javascript and JQuery can be used.

Thanks!


Solution

  • Caveat: I would strongly suggest not doing this, not least because of the potential unintended consequences for users using assistive technology.

    You could watch keypress and keyup and disallow further keypress events until you've seen a keyup. Note that this won't prevent their holding down a key and toggling some other key (like Shift or Ctrl), but it does require them to toggle some key:

    var preventKeypress = false;
    $("textarea")
      .on("keyup", function() {
        // Allow keypresses again
        preventKeypress = false;
      })
      .on("keypress", function(e) {
        if (preventKeypress) {
          // Disallow it
          e.preventDefault();
        } else {
          // Allow it, but then disallow until we next see keyup
          preventKeypress = true;
        }
      });
    <textarea rows="5" cols="50"></textarea>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    I'm not saying it's foolproof, or a good idea... :-)