forked from mpcu/to-do
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
90 lines (75 loc) · 2.63 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
document.addEventListener("DOMContentLoaded", () => {
loadTasks();
const addButton = document.getElementById("addButton");
addButton.addEventListener("click", addTask);
const taskInput = document.getElementById("taskInput");
taskInput.addEventListener("keypress", (e) => {
if (e.key === 'Enter') {
addTask();
}
});
});
function addTask() {
const taskInput = document.getElementById("taskInput");
const taskText = taskInput.value.trim();
const startTime = document.getElementById("startTime").value;
const endTime = document.getElementById("endTime").value;
if (taskText === "") {
alert("Please enter a task before adding.");
return;
}
if (!startTime || !endTime) {
alert("Please enter both start and end time.");
return;
}
const taskList = document.getElementById("taskList");
const li = createTaskElement(taskText, startTime, endTime);
taskList.appendChild(li);
taskInput.value = "";
document.getElementById("startTime").value = "";
document.getElementById("endTime").value = "";
saveTasks(); // Save tasks after adding a new one
}
function createTaskElement(taskText, startTime, endTime, completed = false) {
const li = document.createElement("li");
li.className = completed ? "completed" : "";
li.innerHTML = `
<span>${taskText}</span>
<span class="time">${startTime} - ${endTime}</span>
<button onclick="removeTask(this)">Delete</button>
`;
li.addEventListener("click", toggleTaskCompletion);
return li;
}
function toggleTaskCompletion(e) {
if (e.target.tagName !== "BUTTON") {
const li = e.currentTarget;
li.classList.toggle("completed");
saveTasks(); // Save the new completion status
}
}
function removeTask(button) {
const li = button.parentElement;
li.remove();
saveTasks(); // Save tasks after removing one
}
function saveTasks() {
const taskList = document.getElementById("taskList");
const tasks = [];
taskList.querySelectorAll("li").forEach((li) => {
const taskText = li.firstChild.textContent.trim();
const timeText = li.querySelector(".time").textContent;
const [startTime, endTime] = timeText.split(" - ");
const completed = li.classList.contains("completed");
tasks.push({ text: taskText, startTime, endTime, completed });
});
localStorage.setItem("tasks", JSON.stringify(tasks));
}
function loadTasks() {
const savedTasks = JSON.parse(localStorage.getItem("tasks")) || [];
const taskList = document.getElementById("taskList");
savedTasks.forEach(({ text, startTime, endTime, completed }) => {
const li = createTaskElement(text, startTime, endTime, completed);
taskList.appendChild(li);
});
}