Skip to content
Advertisement

Prevent click event being triggered on children elements

I don’t understand why when I add a click event listener on an element, its children triggers it too.

I want that the parent is triggered even if the children are clicked, which should be the normal behavior I think.

Here’s the code :

var jobsList = document.querySelectorAll('.job_list .job');

for (var i = 0; i < jobsList.length; i++) {
  jobsList[i].addEventListener('click', _onChangeJob, false);
}

function _onChangeJob(e){
  
  // When The children (.job_title, .job_date) is clicked, this function is called. I want only the parent to be clicked event if the children are clicked.
  
}
<div class="job_list">
  <div class="job active" data-job="1">
    <p class="job_title">Job</p>
    <p class="job_date">21.11.16</p>
  </div>
  <div class="job active" data-job="1">
    <p class="job_title">Job</p>
    <p class="job_date">21.11.16</p>
  </div>


</div>

Advertisement

Answer

You can use e.target to check what has been clicked, then for example check if the jobsList collection contains the target element. If it does then one of the .job elements is the target, otherwise the target is a child element.

// convert to a regular array to get indexOf method
var jobsList = [].slice.call(document.querySelectorAll('.job_list .job'));

for (var i = 0; i < jobsList.length; i++) {
  jobsList[i].addEventListener('click', _onChangeJob, false);
}

function _onChangeJob(e){
  if( jobsList.indexOf( e.target ) !== -1 ){
    console.log( 'clicked on .job')
  }
  else {
    console.log( 'clicked on a child element')
  }
}

https://jsfiddle.net/4r7hLua2/

Advertisement