0

Trying to understand event delegation without the use of jQuery. I setup a event listener click on a container div. I want to limit the click to a button within the container. The problem is when the button contains markup, the target is the element within the button and not the button itself. I thought the event would bubble up the DOM and also trigger a mouseEvent on he button as well. This doesn't seem to be the case. Wondering why or what I'm missing? I've seen demos of this working, but can't seem to reproduce it.

http://jsbin.com/qubuma

const clickHandler = e => {
  console.log(e);
  if (!e.target.matches('button')) return
  console.log('Clicked the button!');
}

const container = document.querySelector('.js-container');
container.addEventListener('click', clickHandler);
<div class="container js-container">
  <!-- Plain Button -->
  <button type="button" class="btn js-button">Login</button>

  <!-- SVG Button -->
  <button type="button" class="iconBtn js-button">
        <span class="u-isVisuallyHidden">Close</span>
        <span class="iconBtn-icon">
          <svg class="iconBtn-icon-inner">
            <use xlink:href="#heart"></use>
          </svg>
        </span>
      </button>
</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Warning: I tried running the above code, it hung my browser when I clicked onthe container. – Barmar Feb 16 '17 at 17:10
  • Hmm, I think the hang comes from Stack Snippet's console emulator when it tries to log the event. It eventually finishes. – Barmar Feb 16 '17 at 17:13

0 Answers0