I'm building a todo-list and I only have one function left to build, the function that will make it possible to mark tasks as done. I can't seem to get it to work. Anyone that might be able to steer me in the right direction? The code below is what I have for now and the function should be able to create a line-through when I click on the "done" button.
// The buttot that will mark a task as done
let btnDone = document.createElement("button");
btnDone.classList.add("btnDone");
btnDone.innerHTML = "<i class='fas fa-check'></i>";
btnDone.addEventListener("click", (e) => {
done(e, i);
});
todoLi.appendChild(btnDone);
// The function that should create a line-through on the task that is clicked on
function done(e, i) {
createHtml();
}
You want to create a kind of "toggle button", like this
var myButton = ...;
myButton.addEventListener("click", function() {
this.classList.toggle("toggled");
});
Then you want in your CSS
/* define toggle CSS style */
.toggle {
...
}
/*define the style for the div (or whatever your list item is) following your toggle button */
.toggle ~ div {
text-decoration: line-through;
}
I created a demo in this pen for you >>> https://codepen.io/emekaorji/pen/OJjKEao
// Let's say you have multiple tasks to check, declare a variable to represent all of them
let todoList = document.querySelectorAll("li"); // This represents all todos
// The following is where the whole functionality of the app will be
todoList.forEach(e => { // 'e' represents 'each' todo
let listText = e.querySelector(".task");
let btnDone = document.createElement("button");
e.appendChild(btnDone);
btnDone.innerHTML = "<i class='fas fa-check'></i>";
btnDone.addEventListener("click", () => {
done();
});
// The function that should create a line-through on the task that is clicked on
function done() {
listText.classList.toggle("checked");
btnDone.classList.toggle("btnDone");
}
});
I just took your code and refactored it also added a bit to it, but basically the answer to your question is in the 'function done()'. You just need to toggle the class that will add and remove the strikethrough on the task when you click its button.
listText.classList.toggle("checked");
and the class 'checked' is defined in the style as this:
.checked {
text-decoration: line-through;
opacity: .5;
}
...still check the code pen here