Reputation: 11
I'm trying to toggle classList on the appended children; I've gotten the toggle to work on preexisting but when I add through the user input it won't work any tips on how I might possibly do this? because as of now im at a loss, please help!
var button = document.getElementById("enter");
var ul = document.querySelector("ul");
var input = document.getElementById("userinput");
var list = document.getElementsByTagName("li");
function listDone() {}
function inputLength() {
return input.value.length;
}
function createListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeyPress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeyPress);
function listDoneToggle() {
for (i = 0; i < list.length; i++) {
list[i].addEventListener("click", function() {
this.classList.toggle("done");
});
}
}
listDoneToggle();
Upvotes: 1
Views: 92
Reputation: 25659
You can simply add the event listener to the item you're creating. First, you could extract the event handler in its own named function so it can be used in multiple places, and only have one function to maintain in case a change is needed later:
function applyToggle() {
this.classList.toggle("done");
}
And then, edit your code like so:
function createListElement() {
var li = document.createElement("li");
li.addEventListener("click", applyToggle); // <--
// ...
}
function listDoneToggle() {
for (i = 0; i < list.length; i++) {
list[i].addEventListener("click", applyToggle); // <--
}
}
Optionally, if you want to reuse the list
variable later and have all of your elements (including the ones you created dynamically), you can also push them into this list:
function createListElement() {
var li = document.createElement("li");
li.addEventListener("click", applyToggle);
Array.prototype.push.apply(list, li); // <--
// ...
}
Upvotes: 1