Exploring the concept of event delegation: Understanding the difference between Event.target and

In the MDN Event.target reference, there is an example provided regarding event delegation:

Example of Event Delegation

// Assuming there is a 'list' variable containing an instance of an  
// HTML ul element.
function hide(e) {
    // Unless list items are separated by a margin, e.target should be  
    // different than e.currentTarget
    e.target.style.visibility = 'hidden';
}

list.addEventListener('click', hide, false);

// If some element (<li> element or a link within an <li> element for  
// instance) is clicked, it will disappear.
// It only requires a single listener to do that

Confusing Part of the Example

What I find unclear in this example is the following comment:

// Unless list items are separated by a margin, e.target should be  
// different than e.currentTarget

Question

How can having a margin on <li> elements affect the difference between Event.target and Event.currentTarget?

Answer №1

Consider the distinction between event.target and event.currentTarget as explained in the MDN Event.currentTarget reference:

The key point is that without a margin, it becomes challenging to directly click on the ul element since the li elements completely occupy its space.

However, if there is a margin present, then it becomes feasible to click on the ul, leading to both event.target and event.currentTarget being the same.

function hide(e) {
    document.querySelector("pre").textContent += 'e.target = ' + e.target.nodeName + ", e.currentTarget = " + e.currentTarget.nodeName + "\n";
}

document.querySelector("#list").addEventListener('click', hide, false);
ul {
  border: 2px solid orange;
}
li {
  padding: 10px;
  color: blue;
  margin: 30px;
  border: 1px dashed blue;
}
<pre></pre>
<ul id="list">
  <li>click me
  <li>click me
  <li>click me
</ul>

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

Error in Express JS: Attempting to access properties of an undefined variable (reading '0'). Issue with SQL query

Struggling to insert something in my database and then access it directly after. Due to the asynchronous nature of node.js, my plan doesn't seem to work out. However, I am confident that there is a solution to make this happen. Here's the code sn ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Looping through required fields in jQuery based on a CSS class

Is there a way to loop through required fields marked with <input class="required">? Currently, only the first input in the loop is being evaluated. How can I traverse the DOM using a loop to check all input boxes? Thank you for your help. While I ...

Execution of Promises in sequence

In my current implementation, I have multiple promise functions structured like: return new Promise(function(resolve, reject) { //logic }); cart.getBasket(req) cart.updateBasket(req) cart.updateDefaultShipment(req) cart.getBasketObject(basket) The cod ...

What is preventing the DELETE and PUT methods from functioning on my website?

I am in the process of creating a simple website that functions as a task management application. Each HTTP method has one endpoint, and the methods being used are GET, POST, PUT, and DELETE. These methods need to be linked to functionalities such as addin ...

Display jQuery created hyperlinks in a modal window

I have taken on the task of revamping my school's outdated website. Please excuse the messy CSS and HTML as I am currently in the process of cleaning it up. Additionally, I am not well-versed in Javascript, so... Now, onto the issue at hand. The web ...

Hide <a> by setting its display property to none

Below is the HTML code: <td> <a class="link" href="#"> <span class="download">Link</span> </a> <a class="link" href="#"> <span class="csvdownload">Link 2</span> </a> </td> I am lo ...

Using ng-checked directive with a radio button in AngularJS

Within my angular application, I have implemented a loop to iterate through a collection and display the records using input type="radio". <tr ng-repeat="account in vm.pagedAccounts.items" ng-class="{ 'highlight': (account.row ...

Find the second element beneath the mouse cursor that is not a direct ancestor of the first element

I am currently developing a card drag-and-drop board using HTML5 inspired by Trello. My focus right now is on connecting the lists to specific list slots/containers. My challenge lies in determining which list container is positioned beneath the mouse po ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

increasing the size of an array in react javascript

componentWillMount(){ this.adjustOrder(); } componentDidMount(){} adjustOrder(){ var reorderedArray = []; this.state.reservation1.length = 9; for (var i = 0; i < this.state.reservation1.length; i++) { if(this.state.reservation1[i]){ r ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Marked checkboxes and Node.js

I'm having trouble grasping the concept of using HTML checkboxes with Node.js and Express. I have a basic form in EJS and before diving deeper into the backend logic, I want to ensure that the correct values are being retrieved. Despite my efforts to ...

Changing Color of Specific Sticky Note in React - Customize Color of Individual Note Without Affecting Others

In React, I am working on a basic application for sticky notes that allows users to create as many of them as they'd like. One issue I'm facing is with changing the color of individual sticky notes – currently, when I change the color, it affe ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

React Router isn't displaying any content

I'm facing an issue with react-router-dom where none of my components are rendering and I just see a blank white screen. The content is not being added to my index.html template, even though there are no visible errors. Interestingly, it mentions that ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

Passing a JavaScript variable to PHP resulted in the output being displayed as "Array"

After sending a JavaScript variable with the innerHTML "Basic" to PHP via Ajax and then sending an email with that variable, I received "Array" instead of "Basic". This situation has left me puzzled. HTML: <label class="plan-name">Plan name: <b ...

Is it possible to use the setState function in a React functional component when the form is loading

Implementing a React component using hooks: Requirement: Upon page load, data should populate from the backend into dropdowns and tables with checkboxes. When the Submit button is clicked, the consolidated object of default selected values should be used ...

Having trouble making updates to a MongoDB document through Node.js

I am working on the development of an online course platform and facing an issue while adding new video lectures to a specific course. After creating a course, any attempt to add new content triggers an update request, even when adding video lectures that ...