I feel like I understand focus()
:
- When trying to focus on a form element, like
input
, it "just works", so long as the document is ready. - When trying to focus on a non-form element, like
div
, you must add atabindex
attribute. tabindex
adds the ability to tab to an element in precedence order (higher number the better),0
and up. However, there's a special value,-1
, that explicitly removes the element from the tab order.
- When calling
focus
programmatically, do so within asetTimeout
. - Be sure to make a setTimeout value large enough that it waits for display animations to finish, but not so late that the user has time to do other things, like click or type elsewhere.
Pretty simple, really, right? But no. It just doesn't work for me.
My specific use-case is that I have a key-nav-enabled widget that, if you hit the right key, opens a pop-over modal widget. It works great. But I can't get that modal widget to take focus. That modal widget that has no form inputs (just some text and a close link). I've added keydown/up/press events to the modal widget, I've added tabindex
to various nodes and tried to focus them, but the original widget still gets the keyboard events.
DOM-wise, the modal widget, despite being new
'd up within the keynav widget, is attached to the DOM at the body
level, so it's not like the keyboard events are bubbling up through my modal dialog and should be stopPropagation
'd, it's never getting those events.
What this means is that if you hit another key before you click in the modal widget, it opens a different modal dialog underneath the first modal dialog!
I really hope I'm missing something about focusing div
s, because I have several pieces of functionality I'd like to implement that just aren't working due to (I believe) focus requests simply being ignored.
Help! What am I missing?