Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Interesting question. The heart of the matter is - when does the 'focus' event fire, before or after the blur event? If it fires before the blur event, the problem is easy, because you can just store the current focus in a variable that your blur event can access.</p> <p>However, at least in Chrome 13, it appears the blur event happens <em>before</em> the focus event. One possible solution.</p> <p>Given the following HTML:</p> <pre><code>&lt;input id="foo" value='foo' /&gt; &lt;input id="bar" value='bar' /&gt; </code></pre> <p>You can then:</p> <pre><code>var currentFocus; var pendingBlur; var foo = document.getElementById('foo'); foo.addEventListener('focus', function(){ currentFocus = foo; if(pendingBlur !== undefined){ pendingBlur(); pendingBlur = undefined; } }); foo.addEventListener('blur', function(){ pendingBlur = function(){ console.log('new focus:', currentFocus); }; }); var bar= document.getElementById('bar'); bar.addEventListener('focus', function(){ currentFocus = bar; if(pendingBlur !== undefined){ pendingBlur(); pendingBlur = undefined; } }); bar.addEventListener('blur', function(){ pendingBlur = function(){ console.log('new focus:', currentFocus); }; }); </code></pre> <p>Basically, I just not the blur callback so it is handy for the focus event to call after we know about which element was focused.</p> <p>Here is a <a href="http://jsfiddle.net/BaYJu/" rel="nofollow">working example</a> on JSFiddle.</p> <p>EDIT: This solution suffers from the problem that if you blur on the form by clicking on something <em>other</em> than another form element, the blur event never fires (since we wait for the focus event). The only way around that, that I can conceive, is using a timer to check if pendingBlur is defined, and if so, call it. At which point you don't really need the focus event to call the blur callback anymore...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload