Reputation: 123
I have a question about how to stop a event propagation.
Imagine i have two divs, one container and one contet.
When i make a complete click(mousedown and mouseup) inside the content, i can stop the propagation with preventDefault()
But if i make the mousedown inside the content, the move mouse outside and release the button, then the container handler is triggered.
I dont care about the event in the content, but i need to stop the event going trough the container in this situation.
I made a fiddle to test it: https://jsfiddle.net/Lq7v50nw/
JS:
$('#container').on('click', function(){
alert('click in container')
});
$('#content').on('click', function(ev){
ev.stopPropagation();
alert('click in content')
});
HTML
<div id="container">
<div id="content"></div>
</div>
Is there anyway to achieve that behaviour? Thank you.
Edit (more information about what ive already tried) Change click event for mousedown. The problem with that is they need to click and drag inside the content, and sometimes the drag beyond the content triggering the container handler. I cannot use the mousedown.
Upvotes: 5
Views: 2811
Reputation: 1682
If there are register functions which are getting called multiple time, then multiple re-register may cause this kind of issue. We need to de-register before re-registering it.
$('#youractionidhere').off('click').on('click', function (event) {
//function body
});
Doing .off()
and then .on()
event in sequence will be helpful.
Cheers!!!
Upvotes: 0
Reputation: 19947
You need to stop using the native "click" event, and implement your own synthetic "click" event somehow. You need to listen on both "mousedown" and "mouseup", in order to mimick an "click".
Idea is to attach a one-off "mouseup" handler right inside "mousedown" to synthesize a full "click".
If you "mousedown" in #content, you stopPropagation
and attach "mouseup" only to #content. This way, because #container has no "mouseup" attached, there is no way such synthetic "click" will fire on it.
Upvotes: 1
Reputation: 186
Try using a combination of keyup and mosuseup
$('#container').on('keyup', function(ev){
alert('click in container');
ev.stopPropagation();
});
$('#content').on('mouseup', function(ev){
ev.stopPropagation();
alert('click in content')
});
I hope, it will be useful.
Upvotes: 0
Reputation: 129
Maybe you can solve your problem with "mousedown"?
$('#container').on('mousedown', function(ev){
ev.stopPropagation();
alert('click in container')
});
$('#content').on('mousedown', function(ev){
ev.stopPropagation();
alert('click in content w2')
});
it triggers immediately
Upvotes: 0