I am trying to figure out when a key press is an empty space, so I did the following:
if (e.which == ' '){
}
however this does not work. Any idea why?
event.which returns the code of the character pressed. space key code is 32, so use it instead:
if (e.which === 32) {
//
}
Another way is to convert character to char code with .charCodeAt():
if (e.which === " ".charCodeAt(0)) {
//
}
CHECK: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Write a test code and alert what the keyCode is.
document.onkeypress = function(e) {
e = e || window.event;
console.log(e.keyCode || e.which);
};
Learn to debug and you would not be asking these simple questions.
jQuery would have been
$(document).keypress(
function (e) {
console.log(e.which);
}
);
Probably this is what you're looking for: (Assuming you use the keydown event.)
if(e.keyCode == '32') {
// Your code
}
jsFiddle:
http://jsfiddle.net/DeHFL/
Related
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
Basically, the Chromebook I'm using has trouble distinguishing between alt keys. As you can see in the image below, there's one on the bottom left (second key from the left, which I'll refer to as ALT1), and a smaller one on the bottom right (5th key from right, ALT2).
(source: computershopper.com)
My code has this if function, which is triggered by the alt and enter key:
if (e.altKey && e.keyCode == 13) {
When I press ALT1 and the enter key, the function works as intended. However, when I press ALT2 and the enter key, all it does is trigger the 'enter' event (So, if I'm in a form, it would submit the form).
To try to fix this, I tried using
if (e.keyCode == 18 && e.keyCode == 13) {
However, neither ALT1 or ALT2 work with that. Any ideas?
You can test your two alt key code in this page : http://keycode.info/
Maybe the Chromebook is giving a different code for the two alt key.
In real life, simultanius events rarely exist. What i'm saying is that whatever two keys you try to hit the same time, you won't succeed in doing this at EXACTLY the same time.
you can now use this.
var key1pressed = false;
var key2pressed = false;
$("#somelement").keydown(function(e) {
if(e.which == 13) {
key1pressed = true;
}
if(e.which == 18) {
key2pressed = true;
}
keyspressed();
}).keyup(function(e) {
if(e.which == 13) {
key1pressed = false;
}
if(e.which == 18) {
key2pressed = false;
}
});
function keyspressed() {
if(key1pressed == true && key2pressed == true) {
alert("you pressed these 2 keys together");
}
}
I guess this is what you mean?
Update 2
I used a slightly modified version of my original code.
<script>
window.onkeydown = function (e) {
var enter1 = false;
if (e.keyCode == 13) {
var enter1 = true;
}
if (e.key === 'AltGraph') {
if (enter1 = true) {
//Do what Alt + Enter does
console.log("It worked");
}
}
if (e.altKey && e.keyCode == 13) {
//Do what Alt + Enter does
console.log("It worked");
}
};
</script>
This works like a charm: now both ALT1 and ALT2 work.
Original Answer:
By using this code snippet, I was able to figure out the answer.
document.getElementById("ta").addEventListener("keydown", function(e) {
var keyLocation = ["Standard", "Left", "Right", "Numpad", "Mobile", "Joystick"][e.location];
var message = "Key '" + (e.key || e.keyIdentifier || e.keyCode) + "' is down. Location: " + keyLocation;
this.value += "\n" + message;
e.preventDefault();
}, false);
<textarea id="ta" rows="10" cols="50">Click on here and press some modifier keys such as Shift</textarea>
ALT1 registers as 'Alt', while ALT2 shows up as 'AltGraph'. According to Wikipedia, an AltGraph key is:
AltGr (also Alt Graph, Alt Graphic, Alt Graphics, Alt Grammar, Alt Car, or Right Alt[1]) is a modifier key found on some computer keyboards and is primarily used to type characters that are unusual for the locale of the keyboard layout
Knowing this, I could easily modify my original "if" statement from
if (e.altKey && e.keyCode == 13) {
to this
if (e.altKey && e.keyCode == 13 || e.key === 'AltGraph' && e.keyCode == 13) {
However, I ran into a problem, and haven't been able to figure it out.
if (e.key === 'AltGraph') {
works just fine: however, when I try
if (e.key === 'AltGraph' && e.keyCode == 13) {
it doesn't work. I don't know how, and if anyone can figure out, I'll accept their answer instead. However, for the time being, my answer contains the most relevant info for anyone else who had a similar issue.
UPDATE:
I've figured out the error- however, I can't fix it. This code works fine
if (e.shiftKey && e.key === 'AltGraph') {
It's because I used e.shiftKey instead of e.keycode == 'shift key code'.
However, enter doesn't have the equivalent of this. Using the 'template' below, it works for Shift, Ctrl, and Alt- however, not for enter. Any ideas?
event.[key]Key
For reference, I used these questions to find the answer
Is there a way to detect which side the Alt key was pressed on (right or left)?
Detect Alt Gr (Alt Graph) modifier on key press
it seems simple, but I couldn't figure how to intercept numbers on javascript from Document DOM
$(document).keypress(function (e) {
if (e.keyCode == xx) {
alert();
}
});
Numbers are 48 through 57, so...
$(document).keypress(function (e) {
var key = e.keyCode || e.charCode;
if (key >= 48 && key <= 57) {
alert('You pressed ' + (key - 48));
}
});
See demo
Source: http://www.quirksmode.org/js/keys.html
Keypress events yield a keyCode of 0 in Firefox, and the ASCII character value everywhere else. Keypress events yield a charCode of the ASCII character value in Firefox. Therefore, you should use (e.keyCode || e.charCode) to get the character value.
Also note that your code also wouldn't work because alert should accept one argument. In Firefox, at least, calling alert with no arguments throws an exception.
With those two issues fixed, your code will now be:
$(document).keypress(function (e) {
if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
alert('something');
}
});
Example: http://jsfiddle.net/gRrk6/
$(document).keydown(function(event){
if(event.keyCode == 13) {
alert('you pressed enter');}
});
replace 13 with the keys code, see here for details:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
you should notice the differences between events [ keyCode, charCode, which ]
and this test page affected by the browser i.e i tested it on safari
the onKeyPress always empty
JavaScript Event KeyCode Test Page
I have a button in HTML and I want to provide a shortcut key to it, which should run the functionality as when button clicks what happens.
Is it possible to do something like this using JavaScript or jQuery.
You can do this using plain HTML: accesskey="x". Then you can use alt+x (depending on the browser though if it's alt or something else)
Untested:
$("body").keypress(function(event) {
if ( event.which == 13 ) { // put your own key code here
event.preventDefault();
$("#yourbutton").click();
}
});
It's pretty easy using jQuery. To trigger a button:
$('#my-button').trigger('click');
To monitor for keypress:
$(window).keypress(function (event) {
if (event.which === 13) { // key codes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
event.preventDefault();
$('#my-button').trigger('click');
}
});
Now, if you want to use the Ctrl key or similar you use
if (event.which === 13 && event.ctrlKey)
and similar with event.altKey, event.shiftKey.
$(document).on('keypress', function (e) {
if (e.keyCode === youreKeyCodeHere) {
// if (e.keyCode === youreKeyCodeHere && e.shiftKey === ture) { // shift + keyCode
// if (e.keyCode === youreKeyCodeHere && e.altKey === ture) { // alt + keyCode
// if (e.keyCode === youreKeyCodeHere && e.ctrlKey === ture) { // ctrl + keyCode
$('youreElement').trigger('click');
}
});
Where youreKeyCode can be any of the following javascript char codes , if you're shortcut needs an alt (shift, ctrl ...) use the commented if's . youreElement is the element that holds the click event you whant to fire up.
How to overwrite or remove key events, that is on a website? I'm writing a script for GreaseMonkey and I want to make event on Enter button, but when I press the ENTER button, it triggers function on website.
EDIT 1: Here is the website, that I need to do this http://lockerz.com/auth/express_signup
One of these two should do it for you. I used the first one, although someone on SO told me the second one will work also. I went for the hammer.
Sorry, first one wasn't a cut and paste answer. I use using it to return up/down arrow control on a website. I changed it so that it identifies keycode 13 instead.
(function() {
function keykiller(event) {
if (event.keyCode == 13 )
{
event.cancelBubble = true;
event.stopPropagation();
return false;
}
}
window.addEventListener('keypress', keykiller, true);
window.addEventListener('keydown', keykiller, true);
})();
Searching quickly on SO:
jQuery Event Keypress: Which key was pressed?
Code from there:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
Without a library, use: http://jsfiddle.net/4FBJV/1/.
document.addEventListener('keypress', function(e) {
if(e.keyCode === 13) {
alert('Enter pressed');
return false;
}
});