In the following snippet, why does divClicked()
trigger twice when the <label>
is clicked, but only once when <input>
is clicked?
function divClicked(_index) {
console.log("div click event");
}
function inputClicked(_index) {
console.log("input click event");
}
<div class="option" onclick="divClicked(1)">
<input id="1_1" name="group_1" type="radio" value="1" onclick="inputClicked(1)" />
<label for="1_1">label</label>
</div>
Note: I want to know why this happens, not a "quick fix" like: put onclick() on label.
Why is the onclick event triggered twice? 1 Answers. 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.
This happens because of what the HTML spec describes at 4.10.4:
For example, on platforms where clicking a checkbox label checks the checkbox, clicking the
label
in the following snippet could trigger the user agent to run synthetic click activation steps on theinput
element, as if the element itself had been triggered by the user:<label><input type=checkbox name=lost> Lost</label>
On other platforms, the behavior might be just to focus the control, or do nothing.
This means that when a <label>
is clicked, the browser creates a second "synthetic" click event on the associated <input>
element, in order to toggle its state.
The reason divClicked
is triggered twice, is because the first event which comes from the <label>
bubbles up to the <div>
, and also the second, synthetic click event bubbles up to the <div>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With