-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
63 lines (52 loc) · 1.7 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
document.addEventListener('DOMContentLoaded', () => {
var todoInput = document.getElementById("todo-input")
const addTaskBtn = document.getElementById("add-task")
const todoList = document.getElementById("todo-list")
let tasks =JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach((task) => renderTask(task));
addTaskBtn.addEventListener('click', () =>{
const taskText = todoInput.value.trim();
if (taskText === "") return;
const newTask = {
id: Date.now(),
text: taskText,
completed : false,
}
tasks.push(newTask);
saveTask();
renderTask(newTask);
todoInput.value ="";
console.log(tasks);
})
function renderTask(task){
const li = document.createElement("li");
li.setAttribute("data-id", task.id)
li.innerHTML = `<span>${task.text}</span>
<button id ="del">Delete</button>`;
todoList.appendChild(li);
li.addEventListener("click", (e) =>{
if(e.target.tagname ==='BUTTON') return;
li.classList.toggle('completed')
task.completed =! task.completed;
saveTask();
})
li.querySelector('button').addEventListener('click', (e) =>{
e.stopPropagation();
tasks = tasks.filter((t) => t.id !== task.id );
li.remove()
saveTask()
})
}
function saveTask(){
localStorage.setItem('tasks', JSON.stringify(tasks))
}
})
todoInput.addEventListener("keypress", (event) => {
if (event.key === "Enter"){
alert("hi")
event.preventDefault();
// Trigger the button element with a click
document.getElementById("add-task").click();
}
}
)