Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

The click event bubbles up to ancestor elements.

The focus event does not, and it is the <input> that is being focussed, not the outer element.


Solution 2:

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.


Solution 3:

If you want to attach an event to several elements without an explicit loop, you can use a helper function:

    function attachEvents(elementList, eventName, handlerFunction) {
            if(typeof elementList == "string")
                    elementList = document.querySelectorAll(elementList);
            for(var i = 0; i < elementList.length; i++)
                    elementList[i].addEventListener(eventName, handlerFunction);
    }

You call it like this:

    attachEvents("#area button", "click", function(event) {
            this.style.backgroundColor = "red";
    });

Or like this:

    attachEvents(document.getElementById("area").getElementsByTagName("button"), "click", function(event) {
            this.style.backgroundColor = "red";
    });

You don't always want document.querySelectorAll - doing it yourself means you also do things like some_element.querySelectorAll which is really nice when working with things that aren't yet part of the document, or have no unique selector.

But regardless, putting the loop in a helper function gives you that jquery-esque one-liner without a huge library, it is just a few lines of simple code.


Post a Comment for "AddEventListener For Multiple Elements Doesn't Work With "focus" Event"