Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript listen for all focus/blur events

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?

like image 492
alt Avatar asked Feb 05 '14 08:02

alt


People also ask

What does the blur event do in JavaScript?

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.

Does Focus event 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.

What is Focusin JavaScript?

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.


1 Answers

You can use the focusin and focusout events which bubbles up.

document.addEventListener('focusin', function(e) { console.log('focusin!')})

Demo: Fiddle

like image 140
Arun P Johny Avatar answered Sep 20 '22 14:09

Arun P Johny