Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event delegation, Event.target vs Event.currentTarget

In MDN Event.target reference there is an example about implementing event delegation:

Event delegation example

// 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

Unclear part of the example

What i don't understand in the example is this comment:

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

Question

How can margin on <li> elements make difference between Event.target and Event.currentTarget?

like image 571
maljukan Avatar asked Jun 27 '15 11:06

maljukan


1 Answers

Have in mind what makes event.target different than event.currentTarget as stated in MDN Event.currentTarget reference:

I think the point is that if there's no margin, then it'll be impossible to click directly on the ul since the li elements will entirely fill its space.

If there is a margin, then it'll at least be possible to click the ul, in which case event.target and event.currentTarget will be 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>
like image 136
5 revs, 3 users 90%user1106925 Avatar answered Oct 13 '22 15:10

5 revs, 3 users 90%user1106925