Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Global Element Focus Listener

Tags:

javascript

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
like image 504
ryandlf Avatar asked Apr 08 '13 14:04

ryandlf


People also ask

What is the use of Onfocus in JavaScript?

The onfocus attribute fires the moment that the element gets focus. Onfocus is most often used with <input>, <select>, and <a>. Tip: The onfocus attribute is the opposite of the onblur attribute.

What is Onfocus event?

The onfocus event occurs when an element gets focus. The onfocus event is most often used with <input>, <select>, and <a>. Tip: The onfocus event is the opposite of the onblur event. Tip: The onfocus event is similar to the onfocusin event. The main difference is that the onfocus event does not bubble.


2 Answers

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.

like image 193
user1983983 Avatar answered Sep 19 '22 08:09

user1983983


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.

like image 24
T.J. Crowder Avatar answered Sep 21 '22 08:09

T.J. Crowder