I am learning JavaScript and I am trying to create a tolist. I have successfully been able to add new items to the list and able to cross off when each item is clicked but I need to:
- add a trash can icon when the item is added
- be able to add an event listener to each icon so that is deleted when clicked
Any help would be appreciated!
https://codepen.io/stefan927/pen/qBVLpxm
"<html>
<body onload="taskComplete()">
<div class="card">
<div class="card-body">
<h3 class="card-title" id="header">Today's To Do List</h3>
<form id="todo-form">
<div class="input">
<input type="text" onfocus="this.value=''" class="form-control" id="todo-input"
value="What do I want to do?">
</div>
<div class="form-group">
<input type="button" onclick="addItemToTheList()" class="btn btn-secondary btn-
block" value="Add">
<p> Click an item to cross it off! </p>
</div>
</form>
</div>
<ul class="list-group list-group-flush" id="todo-list">
<li class="list-group-item">Pick up groceries
<i class="fas fa-trash-alt"></i>
</li>
<li class="list-group-item">Finish essay
<i class="fas fa-trash-alt"></i>
</li>
<li class="list-group-item">Soccer @ 5:00
<i class="fas fa-trash-alt"></i>
</ul>
</div>
</body>
</html>"
" // create a function that adds new items to the list with a trash icon
function addItemToTheList() {
const newItem = document.createElement("li");
const input = document.getElementById("todo-input");
newItem.innerHTML = input.value;
input.value = "";
document.getElementById("todo-list").appendChild(newItem);
li.appendChild(i)
// Add click listener
newItem.addEventListener('click', done);
}
function done() {
this.className = "done";
this.removeEventListener('click',done);
}
// Initialize all listener for current undone tasks
function taskComplete() {
var undoneItems = document.getElementsByClassName('undone');
for(var i = 0; i < undoneItems.length; i++){
undoneItems[i].addEventListener('click', done);
}
// Delete item from list when trash icon is clicked
function deleteItem() {
const icon = "fas fa-trash-alt";
const i = document.createElement('i');
const input = document.getElementById("todo-input");
i.onclick = deleteItem;
li.setAttribute('id', input.value);
li.classList.add("list-group-item");
i.className = icon;
}
}"