<h3>Preventing event bubbling</h3>
<p>By using the pointer-events css property</p>
<button id="buttonOne">
<i class="fas fa-times"></i> Icon with events
</button>
<p>Clicking the button will result in a event target of [object HTMLButtonElement] (the button itself)</p>
<p>But clicking the X icon will result in a event target of [object HTMLElement] (the icon element). This is because the event will <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture" target="_blank">bubble up </a>to the button</p>
<button id="buttonTwo">
<i class="fas fa-check"></i> Icon with pointer-events none
</button>
<p>Because of 'pointer-events: none;' clicking the icon in this button will result in a event target of [object HTMLButtonElement] (the button) just like clicking the button would</p>
body {
display: grid;
place-content: center;
min-height: 100vh;
gap: 1rem;
margin: 0;
padding: 0 2rem;
background-color: #04142F;
font-family: sans-serif;
line-height: 1.5rem;
}
button {
padding: 1rem 1.5rem;
font-size: 1.4rem;
background-color: #013BC2;
border: solid 1px #efefef;
border-radius: 0.5rem;
color: #efefef;
}
/* Prevent event bubbling from nested elements inside this button */
#buttonTwo > * {
pointer-events: none;
}
h3 {
margin: 0;
color: #efefef;
}
p {
margin: 0 0 0.5rem 0;
max-width: 50ch;
color: #efefef;
}
p a {
color: #efefef;
}
const buttonOne = document.querySelector('#buttonOne');
buttonOne.addEventListener('click', (e) => {
alert(e.target)
});
const buttonTwo = document.querySelector('#buttonTwo');
buttonTwo.addEventListener('click', (e) => {
alert(e.target)
});
This Pen doesn't use any external JavaScript resources.