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.
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.
CodePudding user response:
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>