Javascript alt key

We create a web user interface that looks like a desktop window. Now we need to process the Alt key. When the Alt key is pressed, focus moves to the top menu.

In Javascript, how to get an event for the Alt key when the Alt ONLY button is pressed? I need to make sure that the other key was not pressed at the same time.

Thanks in advance.

+6
source share
3 answers

I don't know if this was the most elegant solution, but it worked perfectly.

$(function() { //Flag to check if another key was pressed with alt var vAnotherKeyWasPressed = false; //ALT keycode const var ALT_CODE = 18; //When some key is pressed $(window).keydown(function(event) { //Identifies the key var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; //The last key pressed is alt or not? vAnotherKeyWasPressed = vKey != ALT_CODE; }); //When some key is left $(window).keyup(function(event) { //Identifies the key var vKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; //If the key left is ALT and no other key is pressed at the same time... if (!vAnotherKeyWasPressed && vKey == ALT_CODE) { //Focus the menu $('#myMenu').focus(); //Stop the events for the key to avoid windows set the focus to the browser toolbar return false; } }); }); 
+2
source

maybe like that

 document.onkeydown = keydown; function keydown(evt) { if (!evt) evt = event; if (evt.altKey) { alert('alt'); } } // function keydown(evt)​ 
+8
source

Job Demo

 document.onkeyup = KeyCheck; function KeyCheck(e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; switch(KeyID) { case 18: document.Form1.KeyName.value = "Alt"; // do your work on alt key press.... break; case 17: document.Form1.KeyName.value = "Ctrl"; break; } } 

And your html might be like that

 <form name="Form1"> <input type="text" name="KeyName" value="" /> </form> 

Note. If you want to get the alt event on a different control / type than change it with your requirements.

+5
source

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


All Articles