all articles

events fired when label is clicked

2015-07-06 @sunderls

label event click tap js

description, bug

when <label> has for attribute, the events fired at clicking is a little strange, here I've done the test on some browsers.

test result

typechromesafariiOS safari
label for checkbox(sibling)
click label
label:click
input:change
input:click
<- label:touchstart
label: touchend
label: click
input:change
input:click
label for checkbox(sibling)
click input
input:change
input:click
<- input:touchstart
input: touchend
input:change
input:click
label for checkbox(children))
click label
label:click
input:change
input:click
label:click
<- label:touchstart
label: touchend
label: click
input:change
input:click
label:click
label for checkbox(children))
click input
input:change
input:click
label:click
<- input:touchstart
label:touchstart
input: touchend
label:touchend
input:change
input:click
label:click
label for select(sibling))
click label
label:click
input:click
<- label:touchstart
label: touchend
label: click
input:click
input:change (if changed)
label for select(sibling))
click input
input:click (fired right at click)
input:changed(if changed)
input:changed(if changed)
input:click(fired at option is selected)
input:touchstart
input: touchend
input:click
input:change(if changed)
label for select(children))
click label
label:click
input:click
label:click
input:click
label:click
label:touchstart
label: touchend
label: click
input:click
label:click
input:change (if changed)
label for select(children))
click input
input:click
label:click
input:change(if changed)
input:change(if changed)
input:click
label:click
input:touchstart
label:touchstart
input: touchend
label:touchend
input:click
label:click
input:change(if changed)

test code

html

<label for='id1' class="label">label for checkbox(sibling)</label>&lt;input type="checkbox" id="id1" class="input"&gt;&lt;br>

<label for='id2' class="label">label for checkbox(children)&lt;input type="checkbox" id="id2" class="input"&gt;&lt;/label><br>

<label for='id3' class="label">label for select(sibling)</label><select id="id3" class="input"><option value="1">1</option><option value="2">2</option></select><br>

<label for='id4' class="label">label for select(sibling)<select id="id4" class="input"><option value="1">1</option><option value="2">2</option></select></label>

js

$('.label').on('touchstart click touchend', function(e){
 var _for = $(this).attr('for');
 console.log('label ', _for, ':', e.type);
})

$('.input').on('touchstart click touchend change', function(e){
 var id = $(this).attr('id');
 console.log('input ', id, ':', e.type);
})