Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
mpen Avatar asked Jul 17 '11 21:07

mpen


People also ask

Which events is triggered when an element of form loses focus?

The focusout event fires when an element has lost focus, after the blur event. The two events differ in that focusout bubbles, while blur does not. The opposite of focusout is the focusin event, which fires when the element has received focus. The focusout event is not cancelable.

Do focus events bubble?

The main difference is that the onfocus event does not bubble. Therefore, if you want to find out whether an element or its child gets the focus, you could use the onfocusin event. However, you can achieve this by using the optional useCapture parameter of the addEventListener() method for the onfocus event.


1 Answers

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 (i.e. $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.

like image 103
mu is too short Avatar answered Oct 12 '22 22:10

mu is too short