Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox change event bubbles up to parent li element while using e.stopPropagation()

Tags:

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:

  1. eventListener on checkbox change event
const checkbox = document.querySelector(".checkboxContainer input");
checkbox.addEventListener("change", e => {
      e.stopPropagation();
      //rest of code goes here
}):
  1. eventListener on li click event
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 todo 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!

like image 517
PieterT2000 Avatar asked Jan 27 '20 10:01

PieterT2000


1 Answers

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
like image 102
sina_r Avatar answered Oct 02 '22 14:10

sina_r