0

I'm studying the event delegation on a book and I'm not sure I understood very well the concept. I know that it is used to "attach" an event to a parent element instead of attaching it to all the children. But I think I would not be able to use it on my own without a good explanation.

function getTarget(e) {
  if(!e) {
    e = window.event;
  }
  return e.target || e.srcEvent;
}

function itemDone(e) {
  var item, elParent, elGrandparent;
  item = getTarget(e);
  elParent = item.parentNode;
  elGrandparent = item.parentNode.parentNode;
  elGrandparent.removeChild(elParent);

  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

var el = document.getElementById("shoppingList");
if (el.addEventListener) {
  el.addEventListener("click", function(e) {
    itemDone(e);
  }, false);
} else {
  el.attachEvent("onclick", function(e) {
    itemDone(e);
  });
}
<ul id="shoppingList">
  <li class="complete"><a href="itemDone.php?id=1">fresh figs</a></li>
  <li class="complete"><a href="itemDone.php?id=2">pine nuts</a></li>
  <li class="complete"><a href="itemDone.php?id=3">honey</a></li>
  <li class="complete"><a href="itemDone.php?id=4">balsamic vine</a></li>
</ul>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
lewis
  • 91
  • 2
  • 12

1 Answers1

2

If you attach an event to a parent element, and click a child element, if the child element has a click event attached to it that will fire, javaScript will also go down a chain of sorts and fire events attached to parent elements unless you prevent that from happening.

html

<div id="parent">
    <div>child 1</div>
    <div>child 2</div>
    <div>child 3</div>
</div>

javascript

document.getElementById('parent').addEventListener('click', function(e){

    console.log(e.target.innerHTML);

});

jsfiddle

In my example the innerHTML of the child element that is click is logged to the console.

  • Might be nit-picky, but it's preferable to say it will go **up** the chain (as in bubble up). See http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing – Adam Jenkins Jan 31 '17 at 10:52