How to read keyboard state outside keyboard events?

Is there a way to read the state of the keyboard outside the keyboard event handler? In particular, I need to check if the shift key is shifted while the page is loading. I am using jQuery.

+5
source share
5 answers

JavaScript does not query the state of the keyboard. There was a desire. You listen to events and track your status.

+3
source

This code works when you hold the shift key, but it will work on subsequent keystrokes. You can unlock it after the first keystroke, but it also means that it will work even after loading the page.

$(document).ready(function() { $(document).keydown(function(e) { if(e.shiftKey) alert("Shift was held"); }); }); 
+2
source

Stolen and improved from Marco's answer.

 $(document).keydown(function(e) { if(e.shiftKey) alert("Shift was held"); }); 

just deleted $ (document) .ready since you want it at page load time and not after.

+2
source

You can use my KeyboardJS library. It has a method called .getActiveKeys () that tells you which keys are active. The library is really tied to keys and key combos in the usual sense.

I would suggest using event binding.

 KeyboardJS.bind.key('shift', function(){ //logic on key down }, function(){ //logic on key up }); 

Note that you can do complex things like shift + z + x or z + x + c. This works if the shift, z, x are compressed together, or z, x, c are compressed together.

 KeyboardJS.bind.key('shift + z + x, z + x + c', function(){ //logic on key down }, function(){ //logic on key up }); 

You can read which keys are pressed outside the event callback, such as

 var activeKeys = KeyboardJS.getActiveKeys(); 

Hope this helps, Hooray!

+2
source

This is not exactly the solution I expected, but there is an event-based workaround here:

 var shiftKeyState = false; var ctrlKeyState = false; $(document).ready(function () { $(document).bind("keydown keyup click", function (e) { shiftKeyState = e.shiftKey; ctrlKeyState = e.ctrlKey; }); }); 
0
source

Source: https://habr.com/ru/post/1340253/


All Articles