HTML issue on making the whole div clickable (angular)

Issue

Sample HTML Code:

<div class="first-div" (click)="onClickCustomCard(d)">
  Some text..
  Images...
  <input type="checkbox">
</div>

so my problem is that when i try to click the "input type checkbox" it also trigger the onCLickCustomCard(). Is there a way to not auto trigger the onC;ickCustomCard() when i click the input?
Thanks for helping guys…

Solution

You do this by stopping the propagation of events when you click on the input element.

Events can bubble up in the dom tree, meaning that every parent element also receives the event, in your case the click event.

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

Edit, some notes that are not directly related to your question: It’s not good practice to add click events to divs, because this doesn’t make them focusable via keyboard. So you can only click them with your mouse but not tab to them and click them with space or return key. If you use a button or link this behaviour is already implemented for you.

function onClickCustomCard() {
console.log('clicked Card')
}

document.querySelector('.first-div input').addEventListener('click', function(e) {
 e.stopPropagation();
});
<div class="first-div" onclick="onClickCustomCard()">
  Some text..
  Images...
  <input type="checkbox">
</div>

Answered By – cloned

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published