Currently, I am working on creating a basic to-do list purely using JavaScript. Although I have the option to use jQuery to achieve this task easily, I want to stick to plain JavaScript.
I have successfully developed a function that adds a line-through effect as text-decoration for completed tasks. This function targets dynamically added "li" elements using querySelectorAll and loops through the selection to attach an event listener that toggles the line-through effect on click.
To ensure this function works each time a new "li" element is added to the to-do list, I call it within the same loop. However, I noticed that as the number of "li" elements grows in the list, the loop executes multiple times triggering the event repeatedly.
The objective of achieving the line-through effect is fulfilled when the loop runs an odd number of times. Conversely, an even number of iterations fails to produce the desired outcome.
I am now hoping to find a solution to this dilemma by utilizing a for loop. If that is not feasible, I would appreciate any suggestions on the best approach to accomplishing the intended result solely using vanilla JavaScript.
const arrTask = [];
let insertTask = document.querySelector("input");
insertTask.addEventListener("keydown", e => {
if(e.keyCode === 13){
arrTask.push(insertTask.value);
insertTask.value = "";
listTasks()
e.preventDefault();
}
})
const getUlist = document.querySelector("ul");
function listTasks(){
// Add task to the list
let task = document.createElement("li");
task.innerHTML = `${arrTask[arrTask.length-1]}<button class="btn btn-danger deletable"><i class="fa fa-trash"></i></button>`
getUlist.appendChild(task);
task.classList = "list-group-item list-group-item-action taskContainer d-flex justify-content-between align-items-center";
markTasks();
deleteButton();
}
function markTasks(){
// Mark done tasks
let listItem = document.querySelectorAll(".taskContainer");
for(item of listItem){
item.addEventListener("click", function(){
this.classList.toggle("mark")
console.log(this)
})
}
}
You can view my code here: https://codepen.io/minatogawa/pen/oNbOqXp?editors=0011