In MDN Event.target reference there is an example about implementing 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
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
How can margin on <li> elements make difference between Event.target and Event.currentTarget?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With