Suppose I attach an blur 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 blur 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 mySpan 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 blur event on the input element. So I want to check in the blur function if one specific element has been clicked, and if so, ignore the blur event.
Hmm… In Firefox, you can use
explicitOriginalTargetto pull the element that was clicked on. I expectedtoElementto do the same for IE, but it does not appear to work… However, you can pull the newly-focused element from the document: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 theblurevent 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: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).