Consider this simple example:
const formCheck = document.querySelector('.check')
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<input class="check" type="checkbox">
When you check the checkbox, you can see that the event is captured and then logged.
What happens if we then add a label?
Let's do that. If we then leave the code unchanged, appears that a click on a label does also trigger our click event, though it was binded to the checkbox.
const formCheck = document.querySelector('.check')
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<label><input class="check" type="checkbox">A label</label>
That's how it works. But we're not finished yet...
What happens if I bind the event on the label, not on the checkbox?
const formCheck = document.querySelector('label');
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<label><input class="check" type="checkbox">A label</label>
You have seen that correct: the click event triggers two times. But how is it even possible? Let's break down what happens here:
- the label works this way that it triggers a click event in the checkbox
- once you click the label, the event that you binded is triggered
- but since the label itself "clicks" the checkbox, the event is triggered again, because the checkbox is in the label. This way, the event is called twice.
So, what does it mean?
You may have understood that already: the class doesn't change because it toggles two times on a single click. I.e. it toggles and then immediately toggles again, which results in you not noticing any changes.
How can one fix that?
There's a quick fix: you could replace your click event with change event. This way:
- the label triggers checkbox
- the change event on checkbox is called
- the label itself doesn't have a change event, thus everything works as intended
"Working-as-intended" example:
const formCheck = document.querySelector('.drinos-checker')
formCheck.addEventListener('change', function () {
formCheck.classList.toggle('checkerActive')
})
.checkerActive {
background-color: red;
}
<label class="drinos-checker"><input class="drinos-checkbox" type="checkbox" name="checkbox" value="value">Renovation</label>