The javascript event object offers keyCode() and charCode() methods such that charCode() returns 0 for keys that don't cause a character to be displayed like enter, key up, key down, delete, backspace, etc.
I want to check for exactly these characters inside a jQuery keypress event callback, but the jQuery event object doesn't give me access to the mentioned methods.
Can I retrieve the js event object from the jQuery one ?
$('#yourid').bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keycode == 13){
// Enter pressed... do anything here...
}else if(keycode == 46){// delete
}else if(keycode == 8){ // backspace
}
});
Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.
Key code lists are available all over the internet though here is the heavy lifting done for you without depending on any frameworks...
if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}
function keyPressed(evt)
{
var e = evt || event;
var key = e.which || e.keyCode;
if (!powerKeysEnabled) return;
if (showmeallcodes) {alert( key); return;}
switch (key)
{
case 77:// M
alert('m key pressed');
break;
case 76://L
alert('L key pressed');
break;
}
}
Related
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)
I am trying to capture ctrl+z key combination in javascript with this code:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<script type='text/javascript'>
function KeyPress(e) {
var evtobj = window.event? event : e
//test1 if (evtobj.ctrlKey) alert("Ctrl");
//test2 if (evtobj.keyCode == 122) alert("z");
//test 1 & 2
if (evtobj.keyCode == 122 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeypress = KeyPress;
</script>
</body>
</html>
Commented line "test1" generates the alert if I hold down the ctrl key and press any other key.
Commented line "test2" generates the alert if I press the z key.
Put them together as per the line after "test 1 & 2", and holding down the ctrl key then pressing the z key does not generate the alert as expected.
What is wrong with the code?
Use onkeydown (or onkeyup), not onkeypress
Use keyCode 90, not 122
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90 && evtobj.ctrlKey) alert("Ctrl+z");
}
document.onkeydown = KeyPress;
Online demo: http://jsfiddle.net/29sVC/
To clarify, keycodes are not the same as character codes.
Character codes are for text (they differ depending on the encoding, but in a lot of cases 0-127 remain ASCII codes). Key codes map to keys on a keyboard. For example, in unicode character 0x22909 means 好. There aren't many keyboards (if any) who actually have a key for this.
The OS takes care of transforming keystrokes to character codes using the input methods that the user configured. The results are sent to the keypress event. (Whereas keydown and keyup respond to the user pressing buttons, not typing text.)
For future folks who stumble upon this question, here’s a better method to get the job done:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'z') {
alert('Undo!');
}
});
Using event.key greatly simplifies the code, removing hardcoded constants. It has support for IE 9+.
Additionally, using document.addEventListener means you won’t clobber other listeners to the same event.
Finally, there is no reason to use window.event. It’s actively discouraged and can result in fragile code.
Ctrl+t is also possible...just use the keycode as 84 like
if (evtobj.ctrlKey && evtobj.keyCode == 84)
alert("Ctrl+t");
$(document).keydown(function(e){
if( e.which === 89 && e.ctrlKey ){
alert('control + y');
}
else if( e.which === 90 && e.ctrlKey ){
alert('control + z');
}
});
Demo
document.onkeydown = function (e) {
var special = e.ctrlKey || e.shiftKey;
var key = e.charCode || e.keyCode;
console.log(key.length);
if (special && key == 38 || special && key == 40 ) {
// enter key do nothing
e.preventDefault();
}
}
here is a way to block two keys, either shift+ or Ctrl+ key combinations.
&& helps with the key combinations, without the combinations, it blocks all ctrl or shift keys.
90 is the Z key and this will do the necessary capture...
function KeyPress(e){
// Ensure event is not null
e = e || window.event;
if ((e.which == 90 || e.keyCode == 90) && e.ctrlKey) {
// Ctrl + Z
// Do Something
}
}
Depending on your requirements you may wish to add a e.preventDefault(); within your if statement to exclusively perform your custom functionality.
The KeyboardEvent.keyCode is deprecated (link) think about using KeyboardEvent.key instead (link).
So, the solution would be something like this.
if (e.key === "z" && e.ctrlKey) {
alert('ctrl+z');
}
You can actually see it all in the KeyboardEvent when you use keydown event
Use this code for CTRL+Z. keycode for Z in keydown is 90 and the CTRL+Z is ctrlKey. check this keycode in your console area
$(document).on("keydown", function(e) {
console.log(e.keyCode, e.ctrlKey);
/*ctrl+z*/
if (e.keyCode === 90 && e.ctrlKey) { // this is confirmed with MacBook pro Monterey on 1, Aug 2022
{
//your code here
}
});
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
}
}
})
I want to get the keyboard typed text, not the key code. For example, I press shift+f, I get the "F", instead of listen to two key codes. Another example, I click F3, I input nothing. How can I know that in js?
To do it document-wide, use the keypress event as follows. No other currently widely supported key event will do:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
For all key-related JavaScript matters, I recommend Jan Wolter's excellent article: http://unixpapa.com/js/key.html
I use jQuery to do something like this:
$('#searchbox input').on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
EDIT: Since you're not binding to text box use:
$(window).on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
//Enter keycode
//Do something
}
});
http://docs.jquery.com/Main_Page
You can listen for the onkeypress event. However, instead of just examining either the event.keyCode (IE) or event.which (Mozilla) property which gives you the key code, you need to translate the key code using String.fromCharCode().
A good demo is at Javascript Char Codes (Key Codes). View the source and look for the displayKeyCode(evt) function.
Additional references: w3schools - onkeypress Event and w3schools - JavaScript fromCharCode() method.
This is too complicated to answer quickly. This is what I use as the definitive reference for keyboard handling. http://unixpapa.com/js/key.html
Possible Duplicate:
Which keycode for escape key with jQuery
How to detect escape key press in IE, Firefox and Chrome?
Below code works in IE and alerts 27, but in Firefox it alerts 0
$('body').keypress(function(e){
alert(e.which);
if(e.which == 27){
// Close my modal window
}
});
Note: keyCode is becoming deprecated, use key instead.
function keyPress (e) {
if(e.key === "Escape") {
// write your logic here.
}
}
Code Snippet:
var msg = document.getElementById('state-msg');
document.body.addEventListener('keypress', function(e) {
if (e.key == "Escape") {
msg.textContent += 'Escape pressed:'
}
});
Press ESC key <span id="state-msg"></span>
keyCode is becoming deprecated
It seems keydown and keyup work, even though keypress may not
$(document).keyup(function(e) {
if (e.key === "Escape") { // escape key maps to keycode `27`
// <DO YOUR WORK HERE>
}
});
Which keycode for escape key with jQuery
The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.
Update May 2016
keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).
Update September 2018
evt.key is now supported by all modern browsers.
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
alert("Escape");
}
};
Click me then press the Escape key
Using JavaScript you can do check working jsfiddle
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
};
Using jQuery you can do check working jsfiddle
jQuery(document).on('keyup',function(evt) {
if (evt.keyCode == 27) {
alert('Esc key pressed.');
}
});
check for keyCode && which & keyup || keydown
$(document).keydown(function(e){
var code = e.keyCode || e.which;
alert(code);
});
Pure JS
you can attach a listener to keyUp event for the document.
Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
//if esc key was not pressed in combination with ctrl or alt or shift
const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
if (isNotCombinedKey) {
console.log('Escape key was pressed with out any group keys')
}
}
});
pure JS (no JQuery)
document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
//add your code here
}
});
Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.
In this example,
e.preventDefault();
will disable the ESC key-press action.
You may do anything like to hide a div with this:
document.getElementById('myDivId').style.display = 'none';
Where the ESC key pressed is also taken into consideration:
(e.target.nodeName=='BODY')
You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.
window.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
e.preventDefault();
return false;
}
}, true);
Best way is to make function for this
FUNCTION:
$.fn.escape = function (callback) {
return this.each(function () {
$(document).on("keydown", this, function (e) {
var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
if (keycode === 27) {
callback.call(this, e);
};
});
});
};
EXAMPLE:
$("#my-div").escape(function () {
alert('Escape!');
})
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
i think the simplest way is vanilla javascript:
document.onkeyup = function(event) {
if (event.keyCode === 27){
//do something here
}
}
Updated: Changed key => keyCode