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, -
Giving your .select-styled
element the tabindex
attribute (ex: tabindex="1"
) will allow it to receive JavaScript keyboard events.
Explanation:
The jQuery API for .keydown()
mentions that it only works on focusable elements:
It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
Per this previous Stack Overflow answer, <div>
elements are not focusable by default, but DOM Level 2 HTML states that among other rules, any element with a tabindex
can receive focus:
Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:
- HTMLAnchorElement/HTMLAreaElement with an href
- HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
- HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
- Any element with a tabindex
Alternatively, and this might be better practice, you could simply bind your keydown
event handler to the $(document)
when the element receives focus
(which your jQuery already handles without an issue), and unbind it on blur
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With