'function call is not working inside backticks in DOM javascript
I called the function inside the backticks onclick of the input and lis and on fontawesome icon it is not calling the function but the onclick is working as it shows in console. and here is the code.
let editId;
let isEditTask = false;
let todos = JSON.parse(localStorage.getItem('todo-list'));
function showTodo(filter) {
let liTag = '';
if (todos) {
todos.forEach((todo, id) => {
const completed = todo.status === 'completed' ? 'checked' : '';
if (filter === todo.status || filter === 'all') {
liTag += `<li class="task">
<label for="${id}">
<input onclick="updateStatus(this)" type="checkbox" id="${id}" ${completed}>
<p class="${completed}">${todo.name}</p>
</label>
<div class="settings">
<i onclick="showMenu(this)" class="uil uil-ellipsis-v"></i>
<ul class="task-menu">
<li onclick='editTask(${id}, "${todo.name}")'><i class="uil uil-pen"></i>Edit</li>
<li onclick='deleteTask(${id}, "${filter}")'><i class="uil uil-trash"></i>Delete</li>
</ul>
</div>
</li>`;
}
});
}
taskBox.innerHTML = liTag || '<span>You don\'t have any task here</span>';
const checkTask = taskBox.querySelectorAll('.task');
!checkTask.length ? clearAll.classList.remove('active') : clearAll.classList.add('active');
taskBox.offsetHeight >= 300 ? taskBox.classList.add('overflow') : taskBox.classList.remove('overflow');
}
showTodo('all');
filters.forEach((btn) => {
btn.addEventListener('click', () => {
document.querySelector('span.active').classList.remove('active');
btn.classList.add('active');
showTodo(btn.id);
});
});
function updateStatus(selectedTask) {
const taskName = selectedTask.parentElement.lastElementChild;
if (selectedTask.checked) {
taskName.classList.add('checked');
todos[selectedTask.id].status = 'completed';
} else {
taskName.classList.remove('checked');
// todos[selectedTask.id].status = "pending";
}
localStorage.setItem('todo-list', JSON.stringify(todos));
}
I tried to not use backticks and create each of them using createElement. I am still working on that way
Solution 1:[1]
You could use event delegation here, sample example below, we target
uland then the click on particularlielement and do whatever intended to do
const sample = document.querySelector("#sample");
const ul = document.createElement("ul");
sample.append(ul)
const fruits = ["apple","orange","grapes"];
let li = "";
fruits.forEach((fruit)=>{
li += `<li id=${fruit}>${fruit}</li>`;
ul.innerHTML= li;
})
ul.addEventListener("click",function(e){
if(e.target?.tagName === "LI"){
console.log(e.target.innerText)
}
})
<div id="sample"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Codenewbie |
