How do I add an event listener to all the childnodes of a div in and array of those div?
Asked Answered
R

1

7

I'm teaching myself JS and trying to avoid jQuery until my JS skills are better.

Goal: add an eventlistener, for click event, to all the divs of a certain class. Have all the child nodes of that class respond to the event.

My HTML

 <div class="grid-panel six columns">
            <div class="grid-panel-image">
                <i class="fa fa-css3"></i>
            </div>
            <div class="grid-panel-title">
                <h4>css3</h4>
            </div>                  
    </div>
    <div class="grid-panel six columns">
        <div class="grid-panel-image">
            <i class="fa fa-paint-brush"></i>
        </div>
        <div class="grid-panel-title">
            <h4>tamberator</h4>
        </div>
    </div>

I select all the .grid-panel divs using this JS

var gridPanels = document.querySelectorAll('.grid-panel');

then, since that returns an array of divs with the class .grid-panel I add the event listener for click as such

for(i=0; i<gridPanels.length; i++){
    gridPanels[i].addEventListener('click', myFunction);
}

my function is this

 myFunction(){
    var e = event.target;

        switch(e){
            case gridPanels[0]:
            modalArray[0].setAttribute("data-modal-display", "show");
            break
            case gridPanels[1]:
            modalArray[1].setAttribute("data-modal-display", "show");
            break
        }

            console.log(e);
    }

This does work if I click a very specific part of the .grid-paneldiv and the e logs that specific element. However, clicking any children of the div logs the e as the element i clicked, but the eventlistener is not applied to that element. I'm clearly missing something here with this event delegation. I really want the function to fire on the div clicked and all of its childnodes.

Rafael answered 6/3, 2016 at 19:3 Comment(0)
G
4

You're binding correctly, but if you want to get the element to which the handler is bound in the handler, then use this or event.currentTarget instead of event.target.

The event.target represents the actual element that was clicked, which is sometimes useful as well.

Also, you should define the event parameter in the function. Not all browsers have it available as a global variable.

function myFunction(event){
    var e = this
 // var e = event.currentTarget // same as above

    switch(e){
        case gridPanels[0]:
        modalArray[0].setAttribute("data-modal-display", "show");
        break

        case gridPanels[1]:
        modalArray[1].setAttribute("data-modal-display", "show");
        break
    }

    console.log(e);
}
Gussy answered 6/3, 2016 at 19:26 Comment(1)
Wow. That was excellent. Thank you for correcting the event property I was using.Rafael

© 2022 - 2024 — McMap. All rights reserved.