How to stop event bubbling in this code?
-
25-06-2021 - |
سؤال
$('#div1').on('click', '#otherDiv1', function(event){
//Show popup
$('#popupDiv').bPopup({
modalClose: false,
follow: [false, false],
closeClass: 'close'
});
event.stopPropagation();
$('#div2').on('click', '#otherDiv2', function (event) {
// here is ajax request
// close popup
$('#popupDiv').bPopup().close();
event.stopPropagation();
});
}
Click on otherDiv2 calls ajax function many times, how can I stop this?
HTML code
<div id="div2">
<div id="div1"><div id="otherDiv1">Click</div></div>
<div id="popupDiv"><div class="close">X</div>
<input id="otherDiv2" name="otherDiv2" type="submit" value="Click" />
</div>
</div>
popupDiv is created dynamically
When I click on otherDviv1 the popup is open, inside is a button for ajax request. When I click button a request is called and popup closed. If I click one more time otherDiv1 and button a request is called two times and so on.
Thanks
المحلول
Its not necessary to bind a second click
within another click
. Your code bind click
to #otherDiv2
on each click
to #otherDiv1
. For following process don't need stopPropagation()
.
$('#div1').on('click', '#otherDiv1', function(event) {
//Show popup
$('#popupDiv').bPopup({
modalClose: false,
follow: [false, false],
closeClass: 'close'
});
});
$('#div2').on('click', '#otherDiv2', function(event) {
// here is ajax request
// close popup
$('#popupDiv').bPopup().close();
});
But If you need to bind event within another event then first unbind the event from #otherDiv2
and then bind again.
$('#div1').on('click', '#otherDiv1', function(event) {
//Show popup
$('#popupDiv').bPopup({
modalClose: false,
follow: [false, false],
closeClass: 'close'
});
$('#div2').off('click').on('click', '#otherDiv2', function(event) {
// here is ajax request
// close popup
$('#popupDiv').bPopup().close();
});
});
نصائح أخرى
I guess you can use
event.stopImmediatePropagation()
to stop the bubbling.
If you use quite a fresh version of jQuery, every ajax request returns Deferred object which you can store in outer scope of click handler and analyse in order to cancel existing request or just not start new one.
Also there is a concept called throttling, and there are plugins for jquery which does for you.