So I'm trying to make a simple to do list app. I want to add the class "checked" to list items when they are clicked on. I was trying to use event delegation to do this but I don't think I'm doing it correctly. I wasn't sure if I should use "addEventListener" or "onclick." And what is the difference really? I'm sort of new to javascript so if you could explain accordingly I'd appreciate it.
<div id="todoList">
<h1>To Do List</h1>
<form id="todoForm">
<input id="todoInput">
<button type="button" onclick="todoList()">Click Here</button>
</form>
<div id="listText">
<ul id="list">
</ul>
</div>
</div>
The CSS
#todoList {
display: block;
text-align:center;
}
li {
list-style: none;
text-align: left;
border-bottom: 1px solid black
}
#listText {
margin-top: 10px;
margin-left: 30%;
margin-right: 30%;
padding-left: 70px;
padding-right: 85px;
}
ul li.checked {
text-decoration: line-through;
}
The script
function todoList() {
var item = document.getElementById("todoInput").value;
var text = document.createTextNode(item);
var listItem = document.createElement("li");
listItem.appendChild(text);
document.getElementById("list").appendChild(listItem);
}
var ul = document.getElementById("ul");
ul.addEventListener("click", function(e) {
if (e.target.tagName === "li"){
e.target.classList.toggle("checked");
}
});