Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

onclick = () => { 
  // do something
}  

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

A simple idea using delegated listeners attached to the document.

document.addEventListener("click", (e) => {
  console.log("You clicked on " + e.target.nodeName);
}, true);

document.addEventListener("focus", (e) => {
  console.log(e.target.nodeName + " (" + e.target.name + ") has focus");
}, true);

document.addEventListener("blur", (e) => {
  console.log(e.target.nodeName + " (" + e.target.name + ") lost focus");
}, true);
.red {
  background-color: red;
}
<div class='red'>
<p>some text</p>
<input type='text' name='username'>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading