Currently, I am dedicated to learning JS on my own and have decided to hold off on using jQuery until my JavaScript skills have improved.
The objective is to attach an event listener for the click event to all divs of a specific class and have all child nodes of that class respond to the event.
This is how my HTML looks:
<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>
To select all the .grid-panel
divs, I used the following JS:
var gridPanels = document.querySelectorAll('.grid-panel');
Then, as it returns an array of divs with the class .grid-panel
, I added the event listener for the click event like this:
for(i=0; i<gridPanels.length; i++){
gridPanels[i].addEventListener('click', myFunction);
}
Here is my function:
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);
}
While this works when clicking a specific part of the .grid-panel
div and logs that specific element in the e
, clicking any children of the div logs the clicked element as the e
but the event listener is not applied. It seems I am missing something regarding event delegation. I am eager to have the function trigger on the div clicked as well as all its child nodes.