Which HTML element has lost focus?

in javascript when i receive focus event how can i decide which element has lost focus? I am trying to avoid using an onblur event handler for all elements of my web page.

+1


source to share


5 answers


@pbrodka: the target / srcElement property will refer to the element with focus on onfocus events

offhand I don't see a way to get this without onblur, or if the set of objects that you all have focusing methods on, you can store a reference to that object instead. It's also a possible bubble of events that could get you out of jail



it all looks like a bit of a code smell - maybe you need to describe the problem in more detail.

0


source


Hard. You cannot use Delegation Delegation to figure out which control subsequently caused the blur as the focus / blur was not bubbling. There have been some attempts to "fix" this, but they are wrong, not cross browser. May I ask you why you need this information, maybe there is an alternative solution.



0


source


Unfortunately, the onblur event does not bubble, otherwise you could handle it at the window level to always know when an element has lost focus.

Be that as it may, I suppose it would be difficult to do without, as you say, adding an onblur event handler to all elements (a really nasty decision ;-).

0


source


The simplest solution is to write a function that processes all the forms and then all the elements in the form and sets an onblur handler for each (which will probably call some kind of global function). This handler will receive an event and this event will contain the information you are looking for.

So, you just need 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 are dynamically adding forms to your current document. In this case, you need to be sure not to re-install the handler (or you will receive false duplicate events).

0


source


Focus and blur events can be delegated if you follow the PPK guidelines here: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html

0


source







All Articles