This question already has an answer here:
I have an click event on window
. There is also a checkbox and a label for the checkbox. When you click on the label, the window's
click event gets called twice, once for the checkbox, and once for the label.
I tried adding e.stopPropagation();
to the events listener, but it didn't help. Why is the event getting called twice, and what can I do to fix it?
JSFiddle
var checkbox = document.getElementById('checkbox-id');
window.addEventListener('click', function(e) {
console.log(checkbox.checked, e.target)
});
console.clear();
input {
display: none;
}
label {
background-color: orange;
width: 100px;
height: 100px;
display: block;
}
input:checked label {
background-color: green;
}
<input type="checkbox" name="checkbox" id="checkbox-id" />
<label for="checkbox-id"></label>
Aucun commentaire:
Enregistrer un commentaire