Detect AltGr key using JavaScript - javascript

How can I clarify ALT+CTRL and ALTGR key press?
I found this code here as possible solution, but it's doesn't work:
if (event.ctrlKey && event.altKey) {
}
This code is true for alt+ctr and for altGr as well.
I have situation like this: for alt+ctrl+e (for example e, it's no matter) I want one thing and for altGr+e another, how can I do this?
If anyone have some idea, please tell me.

You can detect which key is pressed (from right key or left key) by value of location property in event object. If value of location property is 1 (e.location=1) then left key is pressed. if value is 2 then right key is pressed.
Here I have providing my code for RightAlter+RightCtrl+<any_valid_key>
Check this Example
var isRightAltKey=false;
var isRightCtrlKey=false;
var validKeys=['a','s','d','f','g']; //keep empty array if no need to check key
document.addEventListener("keydown", function(e) {
if(e.key=="Alt"){
// when right Alter pressed make isRightAltKey true
isRightAltKey= (e.location==2);
}
else if(e.key=="Control"){
// when right Control pressed make isRightCtrlKey true,
//if you need any ctrl key pressed then simply set isRightCtrlKey= true;
isRightCtrlKey= (e.location==2);
}
// checking both right key is pressed already or not?
var isRightKeys= isRightAltKey && isRightCtrlKey;
// validate other keys [optional]
var isValidKey=((typeof validKeys === "undefined") || validKeys.length==0 || validKeys.indexOf(e.key.toLowerCase())>=0);
if (isRightKeys && isValidKey){
document.getElementById("detect_key").innerHTML = "RightAlt + RightCtrl + "+e.key;
}
else
{
document.getElementById("detect_key").innerHTML="";
}
}, false);
document.addEventListener("keyup", function(e) {
if(e.key=="Alt"){
// when right Alter released make isRightAltKey false
isRightAltKey= false;
}
else if(e.key=="Control"){
// when right Control released make isRightCtrlKey false
isRightCtrlKey= false;
}
}, false);
<div id="detect_key"></div>
Why attached keyup event listner?
Here we have to detect key location when Ctrl and Alt key is pressed (on keydown event). and we have to store it in flag variable and make it true. when key is released (on keyup event) have to mark as false. Otherwise those flags always remain true. on Next key press it will always true

You can use the location to determined which alt is being pressed.
In order to support Alt+Ctrl we'll save the last location of the pressed Alt.
Location = 1 // Left
Location = 2 // Right
Then, once both Alt and Ctrl are pressed, do your thing. In this example, we'll just write the Alt side in the result div. You can add the "e" pressed condition as well:
if (e.ctrlKey && e.altKey && e.key == "e"){
Example
HTML
<div class="cont">
Click Alt + Ctrl<br /><br />
<div id="res"></div>
</div>
Javascript
var lastAltLocation;
document.addEventListener("keydown", function(e) {
if (e.key == "Alt"){
lastAltLocation = e.location;
}
if (e.ctrlKey && e.altKey){
if (lastAltLocation == 1){
document.getElementById("res").innerHTML = "Left";
}
if (lastAltLocation == 2){
document.getElementById("res").innerHTML = "Right";
}
}
}, false);

Sticking strictly to your question here are the codes for both the required cases:
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.altKey && zEvent.code === "KeyE") {
if(zEvent.ctrlKey) {
//Do Ctrl+Alt+E Stuff Here.
} else {
//Do Alt+E Stuff Here.
}
});
Now breaking down the things going on here. keydown allows you to detect multiple keypresses.
First we check if the Alt and E keys are pressed. If yes, we then go on to check in the Ctrl key is also active and take the appropriate action as needed.

Related

Javascript Replace KeyPress on Input

So I was trying replace the key press "K" with "Z" in an input field.
I was successfully able to do it. But there is a slight delay which makes the user see that the "K" being changed to "Z".
This is my code:
function prinner (event)
{
document.getElementById("txx").innerHTML= event.key; //Displays key pressed on screen by changing text element.
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
if (event.key=="k") // Trying to replace this with z.
{
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval.slice(0,(curval.length-1))+"z";
$("#namaye").val(nval);
}
}
$("#namaye").keyup(prinner);
Does anyone know a better way to achieve this without the delay?
Use keydown instead of keyup and cancel the event so the key stroke doesn't actually get printed:
function prinner (event) {
// Displays key pressed on screen by changing text element.
document.getElementById("txx").innerHTML= event.key;
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
// Trying to replace this with z.
if (event.key=="k") {
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval +"z";
$("#namaye").val(nval);
// Cancel the event
event.preventDefault();
event.stopPropagation();
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<p id="txx"></p>
Use keydown event, and cancel the default behaviour when k is pressed. Also, use selectionStart and selectionEnd properties to replace the characters that were selected at the moment the key was pressed, and to put the cursor at the right position, just after the inserted z:
function prinner (event) {
$("#txx").text(event.keyCode == 32 ? "Space" : event.key);
if (event.key=="k") {
var s = $(this).val();
var i = this.selectionStart;
s = s.substr(0, i) + "z" + s.substr(this.selectionEnd);
$(this).val(s);
this.selectionStart = this.selectionEnd = i + 1;
return false;
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<div id="txx"></div>
Since you use jQuery, use $("#....") instead of the more verbose document.getElementById("...."). Also, in the event handler, this will be input element, so use that reference.
Try using keydown? It happens before the input is actually modified: in fact, if you return false (or e.preventDefault()) inside a keydown listener, it will actually cancel the keystroke, which I think is what you want. Then you manually add your new key. Something like (untested and skipping some details for clarity):
function prinner (event)
{
if (event.key=="k")
{
event.preventDefault() // makes sure the 'k' key never goes to the input
$("#namaye").val( $("#namaye").val() + 'z' );
}
}
$("#namaye").keyup(prinner);
You have to add an event.preventDefault() inside your if clause to stop the event propagation and then you can insert your "z" key.

Respond to click of link while holding key combination in a Google Chrome Extension [duplicate]

How could I identify which Ctrl / Shift / Alt keys are pressed in the following code ?
$("#my_id").click(function() {
if (<left control key is pressed>) { alert("Left Ctrl"); }
if (<right shift and left alt keys are pressed>) { alert("Right Shift + Left Alt"); }
});
Well you this wont work in all browsers just IE 8. Microsoft implemented the ability to determine which (right/left) key was pressed. Here is a link http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx
I also found this wonder article about keypress, keyup, keydown event in browsers.
http://unixpapa.com/js/key.html
$('#someelement').bind('click', function(event){
if(event.ctrlKey) {
if (event.ctrlLeft) {
console.log('ctrl-left');
}
else {
console.log('ctrl-right');
}
}
if(event.altKey) {
if (event.altLeft) {
console.log('alt-left');
}
else {
console.log('alt-right');
}
}
if(event.shiftKey) {
if (event.shiftLeft) {
console.log('shift-left');
}
else
{
console.log('shift-right');
}
}
});
$('#someelement').bind('click', function(event){
if(event.ctrlKey)
console.log('ctrl');
if(event.altKey)
console.log('alt');
if(event.shiftKey)
console.log('shift');
});
I don't know if it's possible to check for left/right keys within a click event, but I don't think it's possible.
e.originalEvent.location returns 1 for left key and 2 for right key. Therefore you can detect which modifier key is pressed like following. Hope this will help you.
var msg = $('#msg');
$(document).keyup(function (e) {
if (e.keyCode == 16) {
if (e.originalEvent.location == 1)
msg.html('Left SHIFT pressed.');
else
msg.html('Right SHIFT pressed.');
} else if (e.keyCode == 17) {
if (e.originalEvent.location == 1)
msg.html('Left CTRL pressed.');
else
msg.html('Right CTRL pressed.');
} else if (e.keyCode == 18) {
if (e.originalEvent.location == 1)
msg.html('Left ALT pressed.');
else
msg.html('Right ALT pressed.');
e.preventDefault(); //because ALT focusout the element
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Press modifier key: </label>
<strong id="msg"></strong>
In most instances the ALT, CTRL,and SHIFT key booleans will work to see if those keys were pressed. For example:
var altKeyPressed = instanceOfMouseEvent.altKey
When called upon, it will return true or false. For more info, go to https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey
For future reference, there is also one called metaKey (NS/firefox only) which works when the meta key is pressed.
Just thought I would add an answer appropriate for 2020.
You can now also use MouseEvent.getModifierState() for this - it's supported by most browsers as of time of writing.
document.addEventListener("click", (evn) => {
const shift = evn.getModifierState("Shift");
const ctrl = evn.getModifierState("Control");
const alt = evn.getModifierState("Alt");
console.log("Mouse pressed! Modifiers:");
console.table({shift, ctrl, alt});
});
Caveats:
Notably, this API does not distinguish between left and right modifiers. If you care about that, you are kind of out of luck. But I imagine this only matters for a small number of use cases.
One of the main benefits of this API is that it supports modifiers other than shift, ctrl, and alt. However the specific behaviour is somewhat erratic across different OSes due to innate platform differences. Check here before you use them.
Following my comment, this is possible solution.
To check which specific modifier key is pressed, you can use KeyboardEvent Location (see table support)
To support IE8, fortunately you could use already posted solution.
Now the workaround is to set a global object with relevant properties regarding which modifier keys are held. Other ways without using global object would be possible of course.
Here, i capture event using relevant javascript listener method (jQuery doesn't support capturing phase). We capture event to handle case where keydown/keyup events propagation would be stopped for some reason by already in-use code.
/* global variable used to check modifier keys held */
/* Note: if e.g control left key and control right key are held simultaneously */
/* only first pressed key is handled (default browser behaviour?)*/
window.modifierKeys = (function() {
/* to handle modifier keys except AltGr which is key shortcut for controlRight + alt */
var mKeys = {};
/* to fire keydown event only once per key held*/
var lastEvent, heldKeys = {};
// capture event to avoid any event stopped propagation
document.addEventListener('keydown', function(e) {
if (lastEvent && lastEvent.which == e.which) {
return;
}
lastEvent = e;
heldKeys[e.which] = true;
setModifierKey(e);
}, true);
// capture event to avoid any event stopped propagation
document.addEventListener('keyup', function(e) {
lastEvent = null;
delete heldKeys[e.which];
setModifierKey(e);
}, true);
function setModifierKey(e) {
mKeys.alt = e.altKey;
mKeys.ctrlLeft = e.ctrlKey && e.location === 1;
mKeys.ctrlRight = e.ctrlKey && e.location === 2;
mKeys.shiftLeft = e.shiftKey && e.location === 1;
mKeys.shiftRight = e.shiftKey && e.location === 2;
}
return mKeys;
})();
/* on div click, check for global object */
$('.modifierKey').on('click', function() {
console.log(modifierKeys);
/* for demo purpose */
$('.info').text(function() {
var txt = [];
for (var p in modifierKeys) {
if (modifierKeys[p]) txt.push(p);
}
return txt.toString();
});
})
/* for demo purpose */
.info:not(:empty) {
border: 1px solid red;
padding: .1em .5em;
font-weight: bold;
}
.info:not(:empty):after {
content: " held";
font-weight: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="modifierKey" tabindex="-1">
DIV to catch modifier keys on click
</div>
<br>
<span class="info"></span>
As side notes:
ALT GR key is a shortcut key for CTRL-Right & ALT
keys
holding simultaneously two indentical modifier keys (e.g Shift-Left &
Shift-Rigth keys), would result in only first one to be handled
(seems like default browser behaviour, so anyway, seems right!)
Use js-hotkeys. It is a jQuery plugin.
This is a test to show what you are looking for. It also shows you how to capture left, right, up, down keys standard and those from numeric key pad (the one with numbers 2,4,6,8)!
http://afro.systems.googlepages.com/test-static-08.html
Easier than anything: you use keydown event to check if it's Ctrl (17) or Shift (16), you then use keyup event to check if it's Enter (13) and Ctrl or Shift hit before (on key down)
cancel Ctrl or Shift on any keyup but Enter
Works like a charm! and on Chrome, Firefox, IE, and Edge too ;) https://jsfiddle.net/55g5utsk/2/
var a=[];
function keyName(p){
var cases = {16:'Shift',17:'CTRL',18:'Alt'};
return cases[p] ? cases[p] : 'KeyCode: '+p;
}
function keyPosition(p){
var cases = {1:'Left',2:'Right'};
return cases[p] ? cases[p]+' ' : '';
}
$('input').on('keydown',function(e){
a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('input').on('keyup',function(){
var c='';
var removeDuplicates = [];
$.each(a, function(i, el){
if ($.inArray(el, removeDuplicates) === -1) {
removeDuplicates.push(el);
c=c+(el)+' + ';
}
});
a=[];
alert(c.slice(0, -3))
});
Following, a version with the click event
http://jsfiddle.net/2pL0tzx9/
var a=[];
function keyName(p){
var cases = {16:'Shift',17:'CTRL',18:'Alt'};
return cases[p] ? cases[p] : '';
}
function keyPosition(p){
var cases = {1:'Left',2:'Right'};
return cases[p] ? cases[p]+' ' : '';
}
$(document).on('keydown',function(e){
a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('#my_id').on('click',function(){
var c='';
var removeDuplicates = [];
a =a.filter(function(v){return v!==''});
$.each(a, function(i, el){
if ($.inArray(el, removeDuplicates) === -1){
removeDuplicates.push(el);
c=c+(el)+' + ';
}
});
if (c) alert(c.slice(0, -3));
a=[];
});
There are some reasons that right and left CTRL,SHIFT & ALT keys are not distinguishable because
1. keyCodes are same
2. Many laptop keyboards may not have two control keys
Taken a Reference :
How can I tell if an event comes from right Ctrl key?

Detecting left and right control keys in Javascript

I have a text input, where I need to bind an event on doing a CTRL-V. I have set a global variable named ctrl which is set to 1 whenever a keydown is fired with a which value of 17. Similarly it is made 0 when a keyup is fired with which value of 17
Problem is, there are two CTRL keys. So if I do something like: first pressing the left CTRL key, and while pressing it down, press the right CTRL key also (so that both CTRL keys are pressed now), and then I release only one of them, the keyup is fired and the variable ctrl is set to 0, even though the other CTRL key is still being pressed.
How do I fire the events such that the variable is set to 0 only when both CTRL keys are up (I don't need to exactly differentiate between them).
Update : this is now possible in modern browsers
The easiest way to detect left and right control keys in Javascript
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (event.location == 1) console.log('left ctrl');
if (event.location == 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: You have to click the inside white space when you run code snippet to activate keyboard keys. This is tested in Chrome and Safari.
There are two properties for this of keydown event.
You can differentiate left and right Ctrl by using
if ( e.location == 1 || e.keyLocation == 1 ) {
var keyPosition = 'left';
} else if ( e.location == 2 || e.keyLocation == 2 ) {
var keyPosition = 'right';
}
I don't think there is a way for that unless you write on lowlevel ... keyCode is the same for both (it is 17)
Just You can use e.ctrlKey as a way to determine if the control key was pressed.
However I read around and found one answer mentioning you could do that in IE but I did not try it from my side
you can use e.originalEvent.location instead of the global event.location
$(document).ready(function(){
$("html").keydown(function(e) {
if (e.ctrlKey) {
if (e.originalEvent.location === 1) console.log('left ctrl');
if (e.originalEvent.location === 2) console.log('right ctrl');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below is your answer for three mouse keyup events. rest for mousewheel you should ask again:
/*
1 = Left Mousebutton
2 = Centre Mousebutton
3 = Right Mousebutton
*/
$(document).mousedown(function(e) {
if (e.which === 3) {
/* Right Mousebutton was clicked! */
alert("right key code 3");
}
else if(e.which === 2) {
alert("Centre key code 2");
}
else if(e.which === 1) {
alert("Left key code 1");
}
});
you can use this:
$('#inputboxinput').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
the cross-browser way:
if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {
event.which = event.charCode || event.keyCode;
}

jQuery handling keypress combinations

I know that when keypress event occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypress combinations through jQuery like ctrl + D ..etc?
In the following code I tried to do something like :
$(document).on("keypress", function(e) {
if( /* what condition i can give here */ )
alert("you pressed cntrl + Del");
});
jQuery already handles this for you:
if ( e.ctrlKey && ( e.which === 46 ) ) {
console.log( "You pressed CTRL + Del" );
}
I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:
NOTE: This example is catching ctrl + space combination, but you can easily change it to any other keys.
var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
$(document).keydown(function(e) {
if (e.ctrlKey) { //If it's ctrl key
ctrlPressed = true; //Set variable to true
}
}).keyup(function(e) { //If user releases ctrl button
if (e.ctrlKey) {
ctrlPressed = false; //Set it to false
}
}); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want
$(document).keydown(function(e) { //For any other keypress event
if (e.which == 32) { //Checking if it's space button
if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
myFunc(); //Do anything you want
ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
}
}
})

Check Ctrl / Shift / Alt keys on 'click' event

How could I identify which Ctrl / Shift / Alt keys are pressed in the following code ?
$("#my_id").click(function() {
if (<left control key is pressed>) { alert("Left Ctrl"); }
if (<right shift and left alt keys are pressed>) { alert("Right Shift + Left Alt"); }
});
Well you this wont work in all browsers just IE 8. Microsoft implemented the ability to determine which (right/left) key was pressed. Here is a link http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx
I also found this wonder article about keypress, keyup, keydown event in browsers.
http://unixpapa.com/js/key.html
$('#someelement').bind('click', function(event){
if(event.ctrlKey) {
if (event.ctrlLeft) {
console.log('ctrl-left');
}
else {
console.log('ctrl-right');
}
}
if(event.altKey) {
if (event.altLeft) {
console.log('alt-left');
}
else {
console.log('alt-right');
}
}
if(event.shiftKey) {
if (event.shiftLeft) {
console.log('shift-left');
}
else
{
console.log('shift-right');
}
}
});
$('#someelement').bind('click', function(event){
if(event.ctrlKey)
console.log('ctrl');
if(event.altKey)
console.log('alt');
if(event.shiftKey)
console.log('shift');
});
I don't know if it's possible to check for left/right keys within a click event, but I don't think it's possible.
e.originalEvent.location returns 1 for left key and 2 for right key. Therefore you can detect which modifier key is pressed like following. Hope this will help you.
var msg = $('#msg');
$(document).keyup(function (e) {
if (e.keyCode == 16) {
if (e.originalEvent.location == 1)
msg.html('Left SHIFT pressed.');
else
msg.html('Right SHIFT pressed.');
} else if (e.keyCode == 17) {
if (e.originalEvent.location == 1)
msg.html('Left CTRL pressed.');
else
msg.html('Right CTRL pressed.');
} else if (e.keyCode == 18) {
if (e.originalEvent.location == 1)
msg.html('Left ALT pressed.');
else
msg.html('Right ALT pressed.');
e.preventDefault(); //because ALT focusout the element
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Press modifier key: </label>
<strong id="msg"></strong>
In most instances the ALT, CTRL,and SHIFT key booleans will work to see if those keys were pressed. For example:
var altKeyPressed = instanceOfMouseEvent.altKey
When called upon, it will return true or false. For more info, go to https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey
For future reference, there is also one called metaKey (NS/firefox only) which works when the meta key is pressed.
Just thought I would add an answer appropriate for 2020.
You can now also use MouseEvent.getModifierState() for this - it's supported by most browsers as of time of writing.
document.addEventListener("click", (evn) => {
const shift = evn.getModifierState("Shift");
const ctrl = evn.getModifierState("Control");
const alt = evn.getModifierState("Alt");
console.log("Mouse pressed! Modifiers:");
console.table({shift, ctrl, alt});
});
Caveats:
Notably, this API does not distinguish between left and right modifiers. If you care about that, you are kind of out of luck. But I imagine this only matters for a small number of use cases.
One of the main benefits of this API is that it supports modifiers other than shift, ctrl, and alt. However the specific behaviour is somewhat erratic across different OSes due to innate platform differences. Check here before you use them.
Following my comment, this is possible solution.
To check which specific modifier key is pressed, you can use KeyboardEvent Location (see table support)
To support IE8, fortunately you could use already posted solution.
Now the workaround is to set a global object with relevant properties regarding which modifier keys are held. Other ways without using global object would be possible of course.
Here, i capture event using relevant javascript listener method (jQuery doesn't support capturing phase). We capture event to handle case where keydown/keyup events propagation would be stopped for some reason by already in-use code.
/* global variable used to check modifier keys held */
/* Note: if e.g control left key and control right key are held simultaneously */
/* only first pressed key is handled (default browser behaviour?)*/
window.modifierKeys = (function() {
/* to handle modifier keys except AltGr which is key shortcut for controlRight + alt */
var mKeys = {};
/* to fire keydown event only once per key held*/
var lastEvent, heldKeys = {};
// capture event to avoid any event stopped propagation
document.addEventListener('keydown', function(e) {
if (lastEvent && lastEvent.which == e.which) {
return;
}
lastEvent = e;
heldKeys[e.which] = true;
setModifierKey(e);
}, true);
// capture event to avoid any event stopped propagation
document.addEventListener('keyup', function(e) {
lastEvent = null;
delete heldKeys[e.which];
setModifierKey(e);
}, true);
function setModifierKey(e) {
mKeys.alt = e.altKey;
mKeys.ctrlLeft = e.ctrlKey && e.location === 1;
mKeys.ctrlRight = e.ctrlKey && e.location === 2;
mKeys.shiftLeft = e.shiftKey && e.location === 1;
mKeys.shiftRight = e.shiftKey && e.location === 2;
}
return mKeys;
})();
/* on div click, check for global object */
$('.modifierKey').on('click', function() {
console.log(modifierKeys);
/* for demo purpose */
$('.info').text(function() {
var txt = [];
for (var p in modifierKeys) {
if (modifierKeys[p]) txt.push(p);
}
return txt.toString();
});
})
/* for demo purpose */
.info:not(:empty) {
border: 1px solid red;
padding: .1em .5em;
font-weight: bold;
}
.info:not(:empty):after {
content: " held";
font-weight: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="modifierKey" tabindex="-1">
DIV to catch modifier keys on click
</div>
<br>
<span class="info"></span>
As side notes:
ALT GR key is a shortcut key for CTRL-Right & ALT
keys
holding simultaneously two indentical modifier keys (e.g Shift-Left &
Shift-Rigth keys), would result in only first one to be handled
(seems like default browser behaviour, so anyway, seems right!)
Use js-hotkeys. It is a jQuery plugin.
This is a test to show what you are looking for. It also shows you how to capture left, right, up, down keys standard and those from numeric key pad (the one with numbers 2,4,6,8)!
http://afro.systems.googlepages.com/test-static-08.html
Easier than anything: you use keydown event to check if it's Ctrl (17) or Shift (16), you then use keyup event to check if it's Enter (13) and Ctrl or Shift hit before (on key down)
cancel Ctrl or Shift on any keyup but Enter
Works like a charm! and on Chrome, Firefox, IE, and Edge too ;) https://jsfiddle.net/55g5utsk/2/
var a=[];
function keyName(p){
var cases = {16:'Shift',17:'CTRL',18:'Alt'};
return cases[p] ? cases[p] : 'KeyCode: '+p;
}
function keyPosition(p){
var cases = {1:'Left',2:'Right'};
return cases[p] ? cases[p]+' ' : '';
}
$('input').on('keydown',function(e){
a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('input').on('keyup',function(){
var c='';
var removeDuplicates = [];
$.each(a, function(i, el){
if ($.inArray(el, removeDuplicates) === -1) {
removeDuplicates.push(el);
c=c+(el)+' + ';
}
});
a=[];
alert(c.slice(0, -3))
});
Following, a version with the click event
http://jsfiddle.net/2pL0tzx9/
var a=[];
function keyName(p){
var cases = {16:'Shift',17:'CTRL',18:'Alt'};
return cases[p] ? cases[p] : '';
}
function keyPosition(p){
var cases = {1:'Left',2:'Right'};
return cases[p] ? cases[p]+' ' : '';
}
$(document).on('keydown',function(e){
a.push(keyPosition(e.originalEvent.location)+keyName(e.keyCode));
})
$('#my_id').on('click',function(){
var c='';
var removeDuplicates = [];
a =a.filter(function(v){return v!==''});
$.each(a, function(i, el){
if ($.inArray(el, removeDuplicates) === -1){
removeDuplicates.push(el);
c=c+(el)+' + ';
}
});
if (c) alert(c.slice(0, -3));
a=[];
});
There are some reasons that right and left CTRL,SHIFT & ALT keys are not distinguishable because
1. keyCodes are same
2. Many laptop keyboards may not have two control keys
Taken a Reference :
How can I tell if an event comes from right Ctrl key?

Categories

Resources