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(){...})
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(){...})
Share
Improve this question
asked Jul 22, 2016 at 2:37
Lin ShenLin Shen
5951 gold badge8 silver badges22 bronze badges
2
-
1
Have you tried
event.stopPropagation()
on a click handler for the child element? – nnnnnn Commented Jul 22, 2016 at 2:39 -
Yes, i've tried
$('.child'').on('click',function(event){ event.stopPropagation()console.log('child click');});
And the funny thing is: the click event of.child
doesn't always triggled, while the mousedown event of.child
and the click event of.parent
works as usual. – Lin Shen Commented Jul 22, 2016 at 2:54
2 Answers
Reset to default 6Mouse events are triggered like this way
MouseDown
Click
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./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>
e.stopPropagation();
e.preventDefault();
e is event passed from function call.
Should do the trick.