views:

3090

answers:

6

in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page.

A: 

@pbrodka: the target/srcElement property would refer to the element with focus for onfocus events

offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out of jail

this all feels like a bit of a code smell though - perhaps you need to describe the problem in more detail

annakata
A: 

Difficult this. You cannot use event delegation to find out which control last produced a blur as focus/blur do not bubble up. There have been some attempts to 'fix' this but they are buggy and not resiliant cross browser. Could I ask you why do you need this information as maybe there is an alternative solution.

redsquare
A: 

Unfortunately, the onblur event doesn't bubble, otherwise you could have handled it at the window level to always know when an element lost focus.

As things are, I do believe it will be hard to do without, as you say, adding an onblur event handler to all elements (a truly nasty solution ;-).

Tor Haugen
A: 

The most simple solution is to write a function that walks all forms and then all elements within the form and installs an onblur handler for each (which will probably call some global function). This handler will get an event and this event will contain the info you seek.

This way, you just have to call this method once in body.onload and it will work no matter how complex your document is.

The only drawback is that you will need to call it if you dynamically add forms to your current document. In this case, you must make sure not to install the handler again (or you will get spurious duplicate events).

Aaron Digulla
This sounds leaky. You'll need to store a reference to each element in some sort of global variable. IE might leak like a sieve.
Rakesh Pai
A: 

thanks everyone for your response and helpful suggestions on who to work out the last element to have focus.

A: 

It is possible to delegate the focus and blur events, if you follow PPK's advice, here: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

Tim Beadle