简体   繁体   中英

Determine what triggered focus event?

I need to determine what caused a focus event.

Ideally, I want to differentiate between a click, a tab/keyboard input, and a manual (via code) trigger.

How can I do this?

I'm looking at the event object, but I'm not seeing anything too useful.

If the focus comes from a $x.focus() call, then the event won't have an originalEvent property because there was no event from the browser so:

if(ev.hasOwnProperty('originalEvent')) {
    // Focus event was manually triggered.
}

To differentiate between keyboard and mouse based focus events, you could try binding a keydown handler to everything else to detect a Tab or Shift-Tab but that would be a gross hack and probably not reliable; for example, on an iPad, you don't hit Tab to move to the next field, you hit Next or Previous in the popup keyboard to move around and those may not register as key presses at all.

There's a similar question about click events that might be of interest as well:

In jQuery, how can I tell between a programmatic and user click?

As you note in the comments, you could trap click events to detect a mouse-based focus change and set a flag somewhere to remember it. Then you'd have this:

  1. If there is no originalEvent in the jQuery event then the focus change was triggered manually (ie $x.focus() or similar).
  2. If the click handler flag is set then the focus change came from a mouse action.
  3. Otherwise the focus change came from a keyboard event.

You'd have to be careful that your click and focus events came in the right order and you'd need to make sure the flag was cleared when you're done with it. This might not be bullet proof but maybe it doesn't need to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM