Reputation: 33644
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?
Upvotes: 0
Views: 100
Reputation: 207501
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);
}
);
Upvotes: 4
Reputation: 3275
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/
Upvotes: 0
Reputation: 145368
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
Upvotes: 6