Skip to content
Advertisement

I need to detect focus event on all HTML input elements on page without addEventListener and without HTML attribute

I need to detect focus event on all HTML input elements on the page without using addEventListener and without HTML attributes

I was able to do that with the click event by:

JavaScript

But when i do like that for onfocus it just fires when the focus occurs in the document itself.

Is there a way I could to it the same way for onfocus and onchange on input and select elements, respectively?

EDIT

The reason why i can’t use the HTML attributes it’s because it will be on a static script that will load through a CDN in the page. Thus, i do not have access to the HTML code itself and i can’t use the HTML attributes.

About the addEventListener, I don’t want use for performance issues, because i would have to loop for every elements and it would be costly for some browsers and devices memories

Furthermore, if the element on pages change dynamically, like in a SPA, i would have to listen to this change and loop through all of them again, which would cause performance issues.

Advertisement

Answer

A simple idea using delegated listeners attached to the document.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement