Forum Moderators: open
1. On window load, get all of the elements that you care whether they have focus. For example, you might do:
var inputs = document.getElementsByTagName("inputs");
and/or
var selects = document.getElementsByTagName("selects");
etc.
You might do this for several types of elements.
2. For each of those nodes, create a new property and set it to false.
for( var i = 0; i < inputs.length; i++ )
{
inputs[i]["focussed"] = false;
3. At the same time, attach an event listener to the object's onfocus and onblur events that will set the value of this new property:
inputs[i].onfocus = function(){this["focussed"] = true;};
inputs[i].onblur = function(){this["focussed"] = false;};
4. Attach a method to return the value of this property:
inputs[i]["isFocussed"] = function(){return this.focussed;};
5. Now you can check either the property or the function to determine if the object has focus. Though it's probably a good idea to add a check for the property or function before you try and use it. For example:
var n = document.getElementById('foo');
if( typeof n.focussed!= "undefined" )
{
if( n.focussed )
{
alert("This node is FOCUSSED!");
}
}
if( typeof n.isFocussed!= "undefined" )
{
if( n.isFocussed() )
{
alert("Yippee!");
}
}
Note, I prefer to use safer methods to attach my event handlers, like using the YAHOO UI Library's Event Utiltiy. The examples above were just for proof of concept. It's possible that other code could overwrite your onfocus and onblur event handlers as they are written above.
Putting it all together:
var inputs = document.getElementsByTagName("input");
for( var i = 0; i < inputs.length; i++ )
{
inputs[i]["focussed"] = false;
inputs[i].onfocus = function(){this["focussed"] = true;};
inputs[i].onblur = function(){this["focussed"] = false;};
inputs[i]["isFocussed"] = function(){return this.focussed;};
}
[edited by: Fotiman at 5:43 pm (utc) on Jan. 8, 2007]