What is the best way to attach an event listener to every child node within a div that is stored in an array of divs?

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.

Answer №1

When binding an element, it is important to consider how to access the element within the handler. Instead of using event.target, it is recommended to use this or event.currentTarget.

While event.target refers to the element that was clicked, it can also be beneficial in certain scenarios.

Additionally, it is essential to define the event parameter within the function as some browsers may not have it 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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

Steps to implement onClick functionality to an array

I am trying to implement an onClick function on this array. When I click on "How will I get cashback?", the output should display. If I click on "Page Page One", it should show "Subcontent" StackBlitz link export default class Chat extends React.Componen ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...

Vue 3's click event handler does not recognize $options.x as a valid function

I'm encountering a perplexing issue. I am currently in the process of creating a Wordpress plugin using Vue, but unfortunately, I am unable to establish functionality for the @click event. <script> export default { name: "App", me ...

Creating a dropdown menu using Vue.js

My latest project involves coding an html page that features a drop-down list using HTML, CSS, and VueJS. The goal is to have something displayed in the console when a specific option from the drop-down list is selected. Here's the snippet of my html ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

Get the maximum width in pixels through JavaScript when it is specified in different units within the CSS

I'm looking to retrieve the max-width value in px from CSS for use in a JavaScript code. The challenge is that this value might be specified in different units in the CSS file. Any suggestions on how to achieve this using JavaScript? const element = ...

Stop unauthorized entry into JavaScript files

Is there a method to secure JavaScript files from unauthorized access? <script src="JS/MyScript.js" type="text/javascript"> It is crucial that users are unable to access the MyScript.js file. I am seeking advice on how to achieve this. Is it even ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Express landing page continuously serves static files

I'm facing an issue with using static files in my project. When a user makes a get request to the "/" landing page, I intend to send non-static data like a JSON response. However, instead of sending "123", it automatically serves my index.html file fr ...

Is it possible to use TypeScript to create objects in a specific pattern from an array of objects and retrieve data using a for loop?

Having trouble with a for loop while converting an array of objects into a single object. In my Node.js app, I have the following object: Currently working on a REST API and need to properly handle the response. [ { "issuer_id" ...

How to dynamically change the class of an element that contains other elements using JavaScript and JQuery

I have created a blog archive with the following format: +Year +Month Title Here is a snippet of the code: <ul> <span class="toggle">+</span> <li class="year">$year <ul> <span ...

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

PayPal Integration with React for Seamless Checkout Experience

I established a small and uncomplicated online store featuring a PayPal checkout system, and it is functioning adequately. Now, I am looking to include detailed information about the purchased products in the transaction history of my PayPal account. This ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

The Django application is failing to interact with the AJAX autocomplete functionality

After typing the term "bi" into the search bar, I expected to see a username starting with those initials displayed in a dropdown list. However, nothing is showing up. Here are the codes I have used: search.html <html> <div class="ui-widget"> ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

Utilizing amCharts Postprocessing for fetching data for visual representation

My goal is to utilize amcharts for displaying data retrieved from my server. Unfortunately, the API format doesn't align directly with amCharts. It seems that I need to utilize the postProcess function to preprocess the data, but I am struggling due t ...