Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

My Event Handler needs to be clicked two times before being triggered

I'm building a To Do List app which you can find on this link: https://codepen.io/tzunhei/pen/WMpPNw

The problem concerns the edit button which has a puzzling behavior. Once I add notes into the list if I don't change the label, the Edit button runs correctly but if I change the text content of the label, the button needs to be triggered two times before returning at the initial state.

It seems that there is a confusion between the two ul.addEventListener but I don't get why.

Thank you in advance for the help.

1 Answer

Steven Parker
Steven Parker
243,656 Points

You have two separate delegated handlers attached to the ul element. One is intended to handle change events on the checkbox, but since it has no filters it also runs when you make a change to the text box. Your click after making a change first fires the change event on the text box, and since part of the handling involves removing and re-attaching the entire li element I'd guess that prevents the click event from also firing.

You can fix this by enclosing the body of the first handler with a test for the element type:

ul.addEventListener('change', (e) => {
  if (e.target.type == "checkbox") {    // only handle checkbox changes
    // (handler code)
  }
});

It works! Thank you Steven!