Home > Blockchain >  How to detect keypresses in jQuery regardless of layout?
How to detect keypresses in jQuery regardless of layout?

Time:01-15

So basically i am trying to connect clicking links to keys in Tampermonkey. First I tried e.which, but it didn't work with different layouts. Then I tried e.code, but for some reason it only detects pressing the B key (see code below). What did I do wrong?

$(document).on("keypress", function (e) {
    if(e.сode == "KeyN") {
        document.getElementById("nextimage").click();
    } else if(e.code == "KeyB") {
        document.getElementById("previmage").click();
    }
});

CodePudding user response:

You can try using the KEY itself instead of the code. The toUpperCase() function will detect lowercase or uppercase :

$(document).on("keypress", function (e) {
    if(e.key.toUpperCase() == "N") {
        alert("yay!")
    } else if(e.key.toUpperCase() == "B") {
        alert("nay");
    }
});

Here's a reference with the different key codes: https://keycode.info/

CodePudding user response:

Try this to read keys.

Make sure you have the JQuery reference.

$(document).keypress(function(event) {
      alert('You pressed - '   event.key.toUpperCase());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and here is javascript in case:

const myText = document.getElementById('myText');
document.addEventListener('keypress', logKey);
function logKey(e) {
  myText.textContent  = e.key.toUpperCase();
  if(e.key.toUpperCase() == 'N')
     alert("You Pressed N  key");
}

and

<p id="myText"></p>
  •  Tags:  
  • Related