Crossbrowser keypress for special keys (arrows, ...) in javascript

I am creating a browser interface to the terminal. I need to catch both characters (alphanumeric, dotted, oblique, ...) and asymmetric keystrokes (arrows, F1-F12, ...). In addition, if the user holds a certain keystroke, it would be nice to get repeated keystrokes (the function should be called repeatedly until the key is released). The same applies to space, characters, ...

I want this to be as cross-browser as possible ( jQuery keypress does not work on this account). I also tried to use the fork jquery.hotkeys.js , but if I understand correctly, I can not grasp how special and symbolic keys only function (need to use keydown keydown for the former and for the latter).

Is there a JS library that will allow me to catch characters and special keys?

I hope I donโ€™t miss something obvious. :)

UPDATE To clarify: I'm looking for a library that would hide information about browser implementation from me.

+6
source share
3 answers

I ended up using keycode.js , but I am creating an entire event management system around keydown, keypress and keyup events, because only one event (keydown) is not enough to determine which character was entered and which key was pressed if there is no corresponding character. Browser incompatibility is an added bonus to this problem. :)

Thank you for your answers, this helped me fully understand the problem.

+1
source

In fact, this is exactly what you need. It captures all the keys, even if you hold the button, it starts several times.

<input type='text' onkeydown='return myFunc(this,event)'> <script> function myFunc(Sender,e){ var key = e.which ? e.which : e.keyCode; if(key == someKey){ // cancel event and do something ev.returnValue = false; if(e.preventDefault) e.preventDefault(); return false; } } </script> 

UPDATE try checking this with jQuery

 $(document).ready(function(){ $('#in').keydown(fn); }); var cnt = 0; function fn(e){ var key = e.keyCode ? e.keyCode : e.which; cnt++; if(cnt == 10) { alert('event was fired 10 times. Last time with key: '+key); cnt = 0; } } 
+4
source

The DOM 3 Events specification includes key events , but it is still a working draft, which is probably not as widely supported, but should be very useful.

To include key codes in characters, you can find Quriskmode . Knowing which key was pressed, and which modifiers should get you where you want to be. Note that you may have problems mapping all keyboards to the same character sets, as some have keys that others do not have (for example, a Microsoft โ€œwindowโ€ key and an Apple key). Some trial and error may be required.

Oh, and you can find the article JavaScript Madness: Events in the keyboard .

+1
source

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


All Articles