javascripthtmldom

Detect loss of focus in JavaScript


I want to be able to detect when arbitrary elements loose focus in JavaScript, so I can build an in-line editing tool similar to jEdit. I can't depend on jQuery for this library, so I need a native method for doing it.

I looked at onblur, which would seem to be the right thing but MDN has a note that suggests it may be IE specific?

In contrast to MSIE--in which almost all kinds of elements receive the blur event--almost all kinds of elements on Gecko browsers do NOT work with this event.

Which elements will/wont work with this, is there a better way to detect such things?

If blur works, should the docs at https://developer.mozilla.org/en-US/docs/DOM/element.onblur be changed?


Solution

  • You can use an onfocusout on the body element. The difference between onblur and onfocusout is that the latter bubbles up, so you don't have to install it for every node that you want.

    Related question: Detect which form input has focus using JavaScript or jQuery