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