Michiel Borkent Michiel Borkent - 2 years ago 195
Javascript Question

When onblur occurs, how can I find out which element focus went *to*?

Suppose I attach an onblur function to an html input box like this:

<input id="myInput" onblur="function() { ... }"></input>

Is there a way to get the ID of the element which caused the onblur event to fire (the element which was clicked) inside the function? How?

For example, suppose I have a span like this:

<span id="mySpan">Hello World</span>

If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was
that was clicked?

PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.

PPS: The background of this problem is that I want to trigger an Ajax.AutoCompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the onblur event on the input element. So I want to check in the OnBlur function if one specific element has been clicked, and if so, ignore the blur event.

Answer Source

Hmm... In Firefox, you can use explicitOriginalTarget to pull the element that was clicked on. I expected toElement to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document:

function showBlur(ev)
   var target = ev.explicitOriginalTarget||document.activeElement;
   document.getElementById("focused").value = 
      target ? target.id||target.tagName||target : '';


<button id="btn1" onblur="showBlur(event)">Button 1</button>
<button id="btn2" onblur="showBlur(event)">Button 2</button>
<button id="btn3" onblur="showBlur(event)">Button 3</button>
<input id="focused" type="text" disabled="disabled" />

Caveat: This technique does not work for focus changes caused by tabbing through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using activeElement (except in IE) is that it is not consistently updated until after the blur event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on the technique Michiel ended up using:

function showBlur(ev)
  // Use timeout to delay examination of activeElement until after blur/focus 
  // events have been processed.
    var target = document.activeElement;
    document.getElementById("focused").value = 
      target ? target.id||target.tagName||target : '';
  }, 1);

This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are clicked (vs. tabbed to).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download