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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With