I'm attempting to capture arrow key presses in jQuery, but no events are being triggered.
$(function(){
$('html').keypress(function(e){
console.log(e);
});
});
This generates events for alphanumeric keys, but delete, arrow keys, etc generate no event.
What am I doing wrong to not be capturing those?
This question is related to
javascript
jquery
keypress
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
Please refer the link from JQuery
http://api.jquery.com/keypress/
It says
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.
That means you can not use keypress in case of arrows.
left = 37,up = 38, right = 39,down = 40
$(document).keydown(function(e) {
switch(e.which) {
case 37:
$( "#prev" ).click();
break;
case 38:
$( "#prev" ).click();
break;
case 39:
$( "#next" ).click();
break;
case 40:
$( "#next" ).click();
break;
default: return;
}
e.preventDefault();
});
$(document).keydown(function(e) {
console.log(e.keyCode);
});
Keypress events do detect arrow keys, but not in all browsers. So it's better to use keydown.
These are keycodes you should be getting in your console log:
$(document).on( "keydown", keyPressed);
function keyPressed (e){
e = e || window.e;
var newchar = e.which || e.keyCode;
alert(newchar)
}
Source: Stackoverflow.com