Search code examples
javascripthtmlfocusonblur

How to determine where focus went?


This has been asked here before, but several years ago, and there was no cross-platform solution at the time (other than the setTimeout solution, which is really not very handy).

I'd like to do onblur="foo(parm);" and have foo be able to determine which element now has focus.

I'm using regular javascript; no jQuery for this one, please.

Is that possible these days?


Solution

  • You can try something like this:

    function whereDidYouGo() {
        var all = document.getElementsByTagName('*');
    
            for (var i = 0; i < all.length; i++)
                if (all[i] === all[i].ownerDocument.activeElement)
                    return all[i];
    }
    

    EDIT:

    function whereDidYouGo() { return document.activeElement; }