Javascript onkeydown percent or five numbers

Is there a way to find out if a user has pressed a percentage key or 5 numbers? It has the same key in FireFox.

+4
source share
4 answers

You can check the modifier keys provided by the event object. event.shiftKey is for your specific use case. In addition, there are event.altKey , event.ctrlKey and event.metaKey (for Windows keys in windows and a command key in MAC keyboards). In the sample code, you will need to perform a check inside the keyCode handler:

 var NUMBER_FIVE = 53; element.onkeydown = function (event) { if (event.keyCode == NUMBER_FIVE) { if (event.shiftKey) { // '%' handler } else { // '5' handler } } }; 

Also, when using event.keyCode you process what the user pressed on the keyboard. If you want to check for specific ASCII characters, you can use event.charCode because this event property tells you which character the user is event.charCode , instead of telling you that the user is tapping the keyboard. Here is the complete guide for this on quirksmode.

+13
source

If you use keydown , 5 and% are the same key code. The event object also has a shiftKey boolean property that tells you if the user is keeping shift.

 document.onkeydown = function (e) { if (e.keyCode === 53) { if (e.shiftKey) { // they pressed % } else { // they pressed 5 } } }; 

If you want to use keypress , these are two different keys:

 document.onkeypress = function (e) { if (e.keyCode === 53) { // they pressed 5 } if (e.keyCode === 37) { // they pressed % } }; 

This site is good for testing keyCodes.

+4
source

Check shiftKey value: jsfiddle

 $(document).keydown(function(e){ if( e.keyCode == 53 ){ if(e.shiftKey){ // % pressed } else{ // 5 pressed } } });​ 
0
source

I am testing both the keyCode and the value of the input character.

 $(document).on({ keypress: function(event){ var charCode = (event.which) ? event.which : event.keyCode; var mFive = String.fromCharCode(event.which); if ((charCode == 53) && (mFive === "5")){ return true; }else if ((charCode == 53) && (mFive !== "5")){ return false; } }); 
0
source

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


All Articles