-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
58 lines (45 loc) · 1.69 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
document.addEventListener('DOMContentLoaded', loadTasks);
const taskInput = document.getElementById('taskInput');
const addTaskButton = document.getElementById('addTaskButton');
const taskList = document.getElementById('taskList');
addTaskButton.addEventListener('click', addTask);
function loadTasks() {
const tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks.forEach(task => {
createTaskElement(task);
});
}
function addTask() {
const taskText = taskInput.value.trim();
if (taskText === '') return;
const task = { id: Date.now(), text: taskText };
createTaskElement(task);
saveTaskToLocalStorage(task);
taskInput.value = '';
}
function createTaskElement(task) {
const li = document.createElement('li');
li.textContent = task.text;
li.setAttribute('data-id', task.id);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', deleteTask);
li.appendChild(deleteButton);
taskList.appendChild(li);
}
function saveTaskToLocalStorage(task) {
const tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
}
function deleteTask(e) {
const li = e.target.parentElement;
const taskId = li.getAttribute('data-id');
li.remove();
removeTaskFromLocalStorage(taskId);
}
function removeTaskFromLocalStorage(taskId) {
let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks = tasks.filter(task => task.id !== parseInt(taskId));
localStorage.setItem('tasks', JSON.stringify(tasks));
}