Detecting left and right control keys in Javascript - 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;
}

Related

Pure JavaScript to detect only Ctrl+Q shortcuts

I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?
document.addEventListener('keydown', function(event){
if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});
I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)
Just ensure none of the other three modifiers are pressed:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
The code below should solve your problem(Updated Code):
document.addEventListener("keydown", function (event) {
var map = [];
onkeyup = function(e){
map.push(e.key);
console.log(map);
if(map.length == 2){
console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
}
onkeydown = function(e){
// console.log(map);
}
}
});
If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!
You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.
Something like this should work:
var keysPressed = [];
function onPressOrRelease(event) {
if (event.type === "keydown") {
if (!keysPressed.includes(event.keyCode))
keysPressed.push(event.keyCode)
} else if (event.type === "keyup")
keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);
let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
if (ctrlQPressed)
console.log("pressed");
}
document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);
You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)

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?

Detect AltGr key using 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.

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