I've added a change event listener input[type='checkbox']
element, but even though I've included the e.stopPropagation()
in my JS code, the event seems to bubble up to the click listener on the <li>
element.
My HTML structure:
<li>
<label class="checkboxContainer">
<input type="checkbox">
<span class="checkmark"></span>
</label>
Lorem ipsum
</li>
It's important to note that that checkbox element doesn't take up any space. Rather, the label element is customized to create a custom checkbox. Adding the eventListener to the label has the same effect.
My JS code:
const checkbox = document.querySelector(".checkboxContainer input");
checkbox.addEventListener("change", e => {
e.stopPropagation();
//rest of code goes here
}):
const li = document.querySelector('li');
li.addEventListener("click", e => {
//code goes here
});
See image below to get a sense of what I want to achieve When I click on the blue area, the todo should fade out (the checkbox event). When I click on the text of the li, the edit screen should toggle. (the li click event) Now when I click the blue area the li event get's triggered to. So the todo fades out and the edit screen shows up.
I would be very grateful for any suggestion how I can solve this problem!
EDIT: if you trigger the click event only on the text (which is all you need according to your example) it works:
const checkbox = document.querySelector(".checkboxContainer input");
const span = document.querySelector('.edit');
checkbox.addEventListener("change", e => {
console.log("only blue fade out")
});
span.addEventListener("click", e => {
console.log("change text")
});
<li>
<label class="checkboxContainer">
<input type="checkbox">
<span class="checkmark"></span>
</label>
<span class="edit">Lorem ipsum</span>
</li>
The problem your are facing is that you are clicking the event on li first.
As soon as you change the checkbox you are first clicking the li as this is the parent element.
const checkbox = document.querySelector(".checkboxContainer input");
checkbox.addEventListener("change", e => {
e.stopPropagation();
console.log("checkbox")
});
const li = document.querySelector('li');
li.addEventListener("click", e => {
console.log("li")
});
// Onchange Checkbox CONSOLE:
li
checkbox
// Onclick li CONSOLE:
li
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