BenQCat BenQCat - 7 months ago 8
HTML Question

AddEventListener for multiple elements doesn't work with "focus" event

I'm guessing I have a basic error in thinking but I just can't get around it.

I have a couple of text fields which I want to add an EventListener to.
I put them all in one class and added the EventListener to this class.
Everyhing works perfect when event of choice is "click". But when I change it to "focus" nothing happens. Why is that?

this works:

document.getElementById('parent').addEventListener('click', emptyField, false);


this doesn not:

document.getElementById('parent').addEventListener('focus', emptyField, false);


text fields:



function emptyField(e){
var clicked = e.target;
if (clicked.value == clicked.name) {
clicked.value='';

if (clicked.id=='password') {
clicked.type='password';
}
}
}

<class id="parent">
<input type="text" name="USERNAME" id="username" value="USERNAME"><br>
<input type="text" name="PASSWORD" id="password" value="PASSWORD" ><br>
</class>




Answer

I think you have to use querySelectorAll() that will return all the inputs :

var fields = document.querySelectorAll('#parent input');

And use loop to attach focus event to every field :

for (var i = 0; i < fields.length; i++) {
    fields[i].addEventListener('focus', emptyField, false);
}

Hope this helps.

Comments