Search code examples
javascriptjqueryjquery-events

Determining whether focus was received as result of a click event


I have an <input> element that can either have the focus set via code, or as the result of a mouse click.

If the user clicks on the input, then the click event handler will fire - all well and good. If the element receives the focus via some other way (e.g. via code) then I want to manually trigger the click event so that the handler will also fire.

I could do this:

$elem = $('input');
$elem
    .on('focus', function() { $(this).trigger('click') })
    .on('click', function() { alert('Clicked!') });

However, this will result in click handler being fired twice; once for the click event and once for the focus event.

Is there any way to selectively trigger the click handler only if the focus was not received as the result of a click event?


UPDATE

This is a very simplified version of my problem, so I can't do things like bind both handlers to the focus event etc. I'm trying to merge two third-party pieces of code.


Solution

  • After doing some more research it appears that there is no way of guaranteeing which event will fire first: click or focus. (There doesn't seem to be a standard that dictates the order of events.)

    This means that when the focus event fires there's no way to determine if a click event will or will not be triggered by the browser shortly afterwards.

    I managed to solve the issue by using setTimeout() to run a test about 100ms after the focus event fired to check if the click event had fired. The third-party code that I was using (bound to the click event) added an extra class to the <input>, so I was able to check for that.