More on Keeping Track of Focus

A bit over a year ago, I wrote a post on Keeping Track of Focus using Javascript.  Unfortunately, the code is severely flawed (though I haven’t yet figured out why it continues to work where I implemented it–but that’s a question for another day).

PPK points out that unlike most javascript events, focus does not bubble. He also offers a solution which uses event capturing to get around the problem.  I’ve taken that solution and modified it for use with Prototype.js as the original version was created that way.

var FocusReader = Class.create({

    initialize: function(){
	this.currentFocus = null;
        var focusRead = this.focusRead.bindAsEventListener(this);
        document.addEventListener("focus", focusRead, true);
        /* Also add the listener for IE which does not
            support capturing */
        document.onfocusin = focusRead;
    },

    focusRead: function(e){
        /* Need to force extending the event since
            it won't be extended by default */
        e = Event.extend(e);
        this.currentFocus = e.element();
    },

    getCurrentFocus: function(){
        return this.currentFocus;
    },

    getCurrentFocusId: function(){
	if(this.currentFocus.identify) return this.currentFocus.identify();
    }

});