I've been working on creating a To-Do list and have managed to add all the necessary functionalities. However, I encountered an issue where the edit function only works the first time it is clicked.
I tried searching for solutions online as I am relatively new to coding, but none of them seemed to solve the problem. The To-Do list allows for editing, saving, and deleting tasks, but the edit function fails to execute after the initial click.
const taskList = document.getElementById('task-list');
const taskInput = document.querySelector('input[type="text"]');
const addButton = document.getElementById('add-button');
window.onload = () =>{
let savedTasks = localStorage.getItem('tasksList');
taskList.innerHTML = savedTasks;
}
addButton.addEventListener('click' , ()=>{
let title = taskInput.value;
const taskElement = document.createElement('li');
taskElement.classList.add('task');
taskElement.innerHTML = `
<input type="checkbox" onclick="window.checked()" class="checkBox">
<span class = "title">${title}</span>
<button class = "edit" onclick="edit()">Edit</button>
<button class = "delete" onclick = "dlt()">Delete</button>
`;
taskList.appendChild(taskElement);
taskInput.value = '';
localStorage.setItem('tasksList', taskList.innerHTML);
});
const edit = ()=>{
let parent = event.target.parentNode;
let title = parent.querySelector('.title');
title.contentEditable = true;
title.focus();
let editBtn = parent.querySelector('.edit');
editBtn.innerText = 'Save';
editBtn.addEventListener('click' , ()=>{
title.contentEditable = false;
editBtn.innerText = 'Edit';
localStorage.setItem('tasksList', taskList.innerHTML);
});
}
const dlt = ()=>{
let parent = event.target.parentNode;
parent.remove();
localStorage.setItem('tasksList', taskList.innerHTML);
}
const checked = ()=>{
let parent = event.target.parentNode;
console.log(parent)
let title = parent.querySelector('.title');
if(parent.querySelector('.checkBox').checked){
title.classList.add('checked');
}
if(!parent.querySelector('.checkBox').checked && title.classList.contains('checked')){
title.classList.remove('checked');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
<link rel="stylesheet" href="./style.css">
<script src="app.js" defer></script>
</head>
<body>
<h1>To-Do List</h1>
<input type="text" placeholder="Add new task">
<button id="add-button">Add</button>
<ul id="task-list">
</ul>
</body>
</html>