I have the following html:
&
Here button click is triggered
. Since the button
is inside the span
and onclick
event is defined for span
the two alert
are happened.
One is by the button
and
other by its parent
(parent have onclick event and button click is triggered).
To avoid two alert, use this
<span>
<button onclick="alert('Boem')" id="test1">test</button>
</span>
I also face this problem on Modal
Solved by the following tricks -
$('#saveButton').off('click').on('click', { modal: modal }, save)
Here off('click')
prevents the save method fires multiple times.
It is calling twice because button is inside a span and span has onclick="alert('Boem')"
, hence when you trigger click on button then it shows alert and same click event propagate to span and shows alert once again.
you need to stop default behaviour of button using below code :
$(function(){
$('#test1').click(function(e){e.preventDefault();}).click();
});
Demo
Bubbling. The click event on the child also happens on the parent (span).
I had the same problem. Mine was the fact that I was using .trigger('.element')
and there were two elements with that element
class.
So, I got more specific, and used .trigger('.parent .element')
to ensure only one click event happened on a single element, instead of one click event on two elements.
I was also getting a similar issue where I had to download a pdf which was downloading twice. I used jQuery's stopImmediatePropagation method.
$( "#test1" ).on("click", function(e) {
e.stopImmediatePropagation();
});
$('#test1').trigger('click');
stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing. Refer here for more details.