ryandlf
ryandlf

Reputation: 28545

Javascript: Global Element Focus Listener

I am trying to set a listener that listens for all focus events. In particular I am trying to listen for anytime an input or textbox gains focus. Per some research, the widely accepted way to achieve this is like this:

document.body.onfocus = function(event) {
   //Check the event.target for input/textbox
   //Do something
};

But the document.body.onfocus doesn't seem to fire, ever. I thought it might be because the document doesn't actually ever receive focus so I tried:

document.body.focus();

To initially "set" the focus, but this doesn't work either.

Any ideas on how I can listen to a focus event on all inputs/textboxes without actually setting the event directly on the element itself? Vanilla javascript only please, I am not using a framework.

Per the accepted answer here is some working code:

var focusHandler = function(event) {
    var type = event.target.nodeName.toLowerCase();
    if(type == 'input' || type == 'textarea') {
        //Do something
    }
};
document.body.addEventListener('focus', focusHandler, true); //Non-IE   
document.body.onfocusin = focusHandler; //IE

Upvotes: 17

Views: 21348

Answers (2)

user1983983
user1983983

Reputation: 4841

As some events (focus, blur, change) do not bubble up, I would recommend you to try Event Capturing instead. First of all onfocus will not work for this, so you have to use addEventListener where you are able to specifiy the used delegation mode in the third argument. Look at MDN for the use of addEventListener.

And take a look at this article for further information about delegating the focus event up.

Upvotes: 14

T.J. Crowder
T.J. Crowder

Reputation: 1074238

The focus event doesn't bubble from elements up to their ancestor elements, so you can't use event delegation (hooking it on body and seeing it for all descendants of body) to detect it.

There's a newer event, focusin (a Microsoft innovation, now also available in other browsers), which does bubble, so that may work for you depending on which browsers you want to support.

Upvotes: 8

Related Questions