When a 'blur' event occurs, how can I find out which element focus went *to*?
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.
setTimeout(function()
{
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).
2015 answer: according to UI Events, you can use the relatedTarget
property of the event:
Used to identify a secondary
EventTarget
related to a Focus event, depending on the type of event.
For blur
events,
relatedTarget
: event target receiving focus.
Example:
function blurListener(event) {
event.target.className = 'blurred';
if(event.relatedTarget)
event.relatedTarget.className = 'focused';
}
[].forEach.call(document.querySelectorAll('input'), function(el) {
el.addEventListener('blur', blurListener, false);
});
.blurred { background: orange }
.focused { background: lime }
<p>Blurred elements will become orange.</p>
<p>Focused elements should become lime.</p>
<input /><input /><input />
Note Firefox won't support relatedTarget
until version 48 (bug 962251, MDN).
I solved it eventually with a timeout on the onblur event (thanks to the advice of a friend who is not StackOverflow):
<input id="myInput" onblur="setTimeout(function() {alert(clickSrc);},200);"></input>
<span onclick="clickSrc='mySpan';" id="mySpan">Hello World</span>
Works both in FF and IE.