So I'd like some JavaScript which listens for all potential focus/blur events on the page. I can do this for click events quite easily:
document.addEventListener('click', function (e) { console.log('click!') })
Any time any element is clicked, the event will trigger, even if the node was inserted after the event listener was added.
I'd like to do the same for focus events, but they are only triggered on individual elements, and never bubble up to the document.
How can I accomplish this? Is the only way to walk the DOM every few seconds and re-listen in case a new input element has been added?
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.
The focus event fires when an element has received focus. The main difference between this event and focusin is that focusin bubbles while focus does not. The opposite of focus is blur . This event is not cancelable and does not bubble.
focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.
You can use the focusin and focusout events which bubbles up.
document.addEventListener('focusin', function(e) { console.log('focusin!')})
Demo: Fiddle
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