Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - not able to catch `@` (at the rate symbol) on keyup event

I have in my code a keyup event and I need to catch the @ character. I'm using this code:

$(function() {
  $("#textbox").keyup(function(e) {
    var keynum = e.keyCode;
    if (keynum && e.shiftKey && keynum == 50) {
      // Made a small change.
      console.log("You pressed @ and value is: " + e.target.value);
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="textbox" />

Now, the problem is that it doesn't work whenever user types shift+2 a little faster

EDIT

You can reproduce this problem by releasing the modifier (shift key) a few milliseconds before the other (2 on my keyboard) key, i.e typing shift + 2 really fast.

@ConstantinGroß was able to address this problem and has a workaround. Please check the accepted answer below.

like image 629
Sumit Wadhwa Avatar asked Mar 04 '23 06:03

Sumit Wadhwa


1 Answers

You could use KeyboardEvent.key (e.key vs e.keyCode): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

$("#textbox").keyup(function(e) {
  if (e.key === '@') {
    console.log("You pressed @ and value is: " + e.target.value);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="textbox" />
like image 94
Tanner Avatar answered Mar 15 '23 01:03

Tanner