Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript click event triggers twice

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.

like image 908
Zze Avatar asked Apr 03 '17 00:04

Zze


People also ask

Why click event triggered twice?

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.


1 Answers

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 the input 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>.

like image 63
4castle Avatar answered Oct 12 '22 02:10

4castle