Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(){...})
like image 608
Lin Shen Avatar asked Oct 29 '25 08:10

Lin Shen


2 Answers

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>
like image 75
Sergey Gornostaev Avatar answered Oct 30 '25 20:10

Sergey Gornostaev


e.stopPropagation();
e.preventDefault();

e is event passed from function call.

Should do the trick.

like image 35
Hardik Vaghani Avatar answered Oct 30 '25 22:10

Hardik Vaghani