How to add an event listener to all children of a div and an array of these divs?

I teach myself JS and try to avoid jQuery while my JS skills are better.

Purpose: Add an eventlistener for the click event for all sections of a particular class. Ask all the children of this class to 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 div .grid-panel using this JS

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

then since this returns an array of divs with the class .grid-panel I am adding an event listener for the click as such

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

My function is

  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 works if I click on a very specific part of the .grid-panel div and e logs for a specific element. However, clicking on any child log entries of div e as the element I clicked, but the eventlistener does not apply to this element. I am clearly missing something here with this delegation. I really want the function to run when I click on the div and all its children.

+7
javascript arrays events delegation
source share
1 answer

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

event.target is the actual element that was clicked, which is sometimes also useful.

In addition, you must define the event parameter in the function. Not all browsers are 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); } 
+3
source share

All Articles