This question already has answers here:
Call function on keydown (Ctrl + Enter) in React
(2 answers)
Closed 2 years ago.
For example, I when press ctrl+s it will call an action to save something; or when I press combination ctrl + z it will undo an action.
I tried to handle onKeyPress event on div but it doesn't work
<div
onKeyDown={() => {
console.log("key press");
}}
>
...
</div>
You can use Javascript to create a function where you record what you have pressed in an array (on keydown) and then on keyup check that array to see if it includes certain key combinations and then return the desired function if the condition is met. Then clear the array after. Like so:
let pressed = [];
document.addEventListener('keydown', function(event) {
pressed.push(event.which);
return (function() {
function checkKeys(key1, key2) {
return pressed.includes(key1) && pressed.includes(key2)
}
document.addEventListener('keyup', function() {
if (checkKeys(17, 90)) { //ctrl + z - insert the keycodes here
// call the UNDO function
} else if (checkKeys(17, 83)) { //ctrl + s - insert the keycodes here
// call the SAVE function
}
pressed = [];
});
})();
});
You can use this website to check what the keycodes are for all the different keys.
Check out a JSFiddle example here. Just make sure you focus on the display window when you press the keys.
you can go with below code:
<div
onKeyDown={(event) => {
if(event.ctrlKey && event.key === "Z") {
console.log("Ctrl+z captured")
}
}}
>
...
</div>
Related
I need the script for functioning the window.location only after pressing the ENTER key 3 or n times.
This is my current code and i am trying to modify it. Need help, still.
function KeyPress(f) {
var event = window.event? event : f
if (event.keyCode == 13)
window.location = './index.html';
}
document.onkeypress = KeyPress;
Following your instructions, after three press to the key ENTER, it should run the code that will call window.location. In this example, I'm using console.log to prove it is doing what you asking.
Note: When you run it, you need to click with the mouse where it says "Press Enter 3 times.". In this way, the browser will focus on that section. Then, you can press the ENTER key three times.
document.addEventListener("keyup", (e) => enterKeyPressed(e))
let counter = 1;
function enterKeyPressed(event) {
console.log("Key", event.keyCode, " Pressed:", counter);
if (event.keyCode == 13 && counter == 3) {
console.log("Enter key is pressed");
// window.location = "<url you want to go>";
return true;
}
counter++;
return false;
}
Press Enter 3 times.
Check the log.
This question already has answers here:
Detecting combination keypresses (Control, Alt, Shift)?
(5 answers)
Closed 2 years ago.
So on my website, I want to make a little box that shows the current mouse position only when I hold Alt+Z and disappear when I release the hotkey.
You can listen for a shortcut (an event) using the addEventListener method:
document.addEventListener('keyup', function (event) {
if (event.key == "z" && event.altKey){
console.log("Alt + Z pressed!")
// Do some other stuff here
}
})
This applies to the entire document; If you want to only add the listener for a certain element, this method would exist for that HTMLElement too.
Here's a live jsfiddle demo.
You can do that by adding the next method to the document.onkeyup event:
document.onkeyup = function(e) {
if (e.altKey && event.key == "z") {
alert("ALT + Z keys were pressed");
}
};
This should solve your problem.
window.addEventListener("keydown", e => {
if(e.keyCode == 90 && e.altKey) alert("Hello World!");
});
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?
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.
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?