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) {
};
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') {
}
};
document.body.addEventListener('focus', focusHandler, true);
document.body.onfocusin = focusHandler;
source
share