Lin Shen Lin Shen - 4 months ago 19
jQuery Question

How to stop a parent's click event when the child's mousedown event is fired

As described in the title, I want to stop a parent's click event when the child's mousedown event is fired.

My HTML code looks like this

<div class='parent'>
<div class='child'></div>
</div>


my jquery code looks like this

$('.child').mousedown(function(){
//what can I write here to prevent parent's click event from fireing?
//I've tried event.stopPropagation() as well as
//event.stopImmediatePropagation() already
});

$('.parent').on('click',function(){...})

Answer

Mouse events are triggered like this way

  1. MouseDown

  2. Click

  3. MouseUp

event.stopPropagation() in mousedown handler only affects on mousedown event. You can try this workaround:

var mdFaired = false;

$('.parent').click(function(e) {
  if(!mdFaired) {
      var counter = $(this).children('.counter');
      var count = parseInt(counter.text());
      counter.text(++count);
  }
  else {
    mdFaired = false;
  }
});

$('.child').mousedown(function(e) {
  e.stopPropagation();
  mdFaired = true;
  
  var counter = $(this).children('.counter');
  var count = parseInt(counter.text());
  counter.text(++count);
});
div {
  border: 1px solid black;
  padding: 5px;
}

.parent {
  width: 300px;
  height: 300px;
}

.child {
  width: 50%;
  height: 50%;
  margin: 50px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='parent'>
  <span class="counter">0</span>
  <div class='child'>
    <span class="counter">0</span>
  </div>
</div>