Keeping Track of Focus
One annoying limitation of Javascript is that there is no easy way to track which element currently has focus. In general, we don't really need this information; however, I've recently run across a case where it would be a good idea to be able to know which element currently has focus. Here's a little prototype based Javascript that provides a simple way to track focus throughout your document using event delegation:
var FocusReader = Class.create({ initialize: function(){ this.currentFocus = null; var focusRead = this.focusRead.bindAsEventListener(this); document.observe("focus", focusRead); }, focusRead: function(e){ this.currentFocus = e.element(); }, getCurrentFocus: function(){ return this.currentFocus; }, getCurrentFocusId: function(){ if(this.currentFocus.identify) return this.currentFocus.identify(); } });
Notice how we've used event delegation to ensure that we can see the focus anywhere in the document without having to add an event handler to every element that may receive focus. We've also provided two ways to represent the focused element--a pointer to the element itself as well as its ID.
Download: focusReader.js (1kb)
I am a User Interface Engineer working for AutoTrader.com in Atlanta, GA and I've been on this crazy ride called Web Development since 1997. Along the way, I'd like to think I've learned a bit and this is my forum to share it.
