Toggle multiple classes on dynamic div

Here’s the full Codepen. You enter a habit and a div is created. You then select the button for each day to toggle through and mark the habit as completed(yes), not completed(no), skipped, or leave blank.

Issue: The toggle classes are not working on some of the additionally added habits/divs. I can’t figure out a pattern on why some work and some don’t. I’m thinking it has to do with the fact that the divs are dynamically added. Any help would be greatly appreciated! Ideally in either JS or JQuery please.

Try using an element for the toggle click handler that is not added dynamically like .container and use e.target instead of this for its logic.

Thank you for the response! I applied your suggestions and it does work better than it did (fewer errors), but I do still get the toggle glitch in some scenarios. For example, if I add two habits back to back, and then select a button under either of those habits it only toggles between ‘blank’ or ‘no’. I’ll work on my toggle functionality, if you have any suggestions I’d welcome them!

You need to move the toggle colors handler code out of the keypress function. Put it below it.

Edit: just in case what I said is unclear.

$("input:text").keypress(function(e) {
...code
});

//TOGGLE BETWEEN COLORS
$(".container").click(function(e) {
...code
});
1 Like

YES! Thank you so much

1 Like

No problem, happy coding!