Event bubbling and delegation

Event bubbling

document.querySelector('.card-title').addEventListener('click', 
  function(e) {
    console.log('card title');
  });

  document.querySelector('.card-content').addEventListener('click', 
  function(e) {
    console.log('card content');
  });

  document.querySelector('.card').addEventListener('click', 
  function(e) {
    console.log('card');
  });

  document.querySelector('.col').addEventListener('click', 
  function(e) {
    console.log('col');
  });

Event delegation

Remove element by click event

document.body.addEventListener('click', deleteItem);

function deleteItem(e){
  if(e.target.parentElement.classList.contains('delete-item') ){
    console.log('Delete item');
    e.target.parentElement.parentElement.remove();
   }
}

HTML

<ul class="collection">
    <li class="collection-item">List Item 1
      <a href="#" class="delete-item secondary-content"><i class="fa fa-remove"></i></a>
    </li>
    <li class="collection-item">List Item 2
      <a href="#" class="delete-item secondary-content"><i class="fa fa-remove"></i></a>
    </li>
</ul>
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *