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.
javascript arrays events delegation
Tamb
source share