Javascript: background image listener

I am trying to install a listener that listens for all focus events. In particular, I try to listen to the focus of an input or text field at any time. According to some studies, the generally accepted way to achieve this is as follows:

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

But document.body.onfocus doesn't seem to work, ever. I thought this could be because the document is not really getting the focus, so I tried:

document.body.focus();

Initially "set" the focus, but this also does not work.

Any ideas on how I can listen to the focus event on all inputs / text blocks without actually setting the event directly on the element itself? Vanilla javascript only, please, I do not use the framework.

In accordance with the accepted answer, here is the 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
+5
source share
2 answers

Since some events (focus, blur, change) do not bubble, I would recommend trying instead Event Capturing. First of all, onfocusit won’t work for this, so you need to use addEventListenerwhere you can specify the delegation mode used in the third argument. See MDN for use addEventListener.

Take a look at the article for more information on delegating a focus event.

+5
source

focus -, ( body body), .

focusin ( Microsoft, ), , , .

+3

All Articles