I’m using jQuery 1.12. I want a DIV to capture key presses (specifically, down nd up arrows), when it has the focus. So I followed this
$('div.select-styled').bind('keydown', function(event) {
console.log(event.keyCode);
elt = $(this).search(".select-options li:hover");
console.log(elt);
switch(event.keyCode){
// case up
case 38:
console.log(“up pressed.”)
break;
case 40:
console.log(“down pressed”)
break;
}
});
but this is not capturing the key presses. See my Fiddle here — http://jsfiddle.net/cwzjL2uw/10/ . Click on the “Select State” menu, or click on the “Last Name” field and click “Tab” to give focus to the next DIV. However, when that menu has focus, clicking on any key doesn’t activate the handler above, at least it didn’t for me on Mac Chrome or Firefox.
Grateful for any help, -
The problem is that, when you press tab
, the focus is on .select
instead of .select-styled
div element
, since .select
is the parent which holds the rest of the elements within. So you probably might need to bind your keydown
onto .select
.
$(".select").on('keydown',function(event) {
console.log(event.keyCode);
elt = $(this).search(".select-options li:hover");
console.log(elt);
switch(event.keyCode){
// case up
case 38:
break;
case 40:
break;
}
});
Here's the Updated Fiddle