forked from Dev2kod/Todo-List
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
79 lines (71 loc) · 2.2 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
let todoList = [];
let completedList = [];
// render todo list
function renderTodoList() {
const todoListElement = document.getElementById('todo-list');
todoListElement.innerHTML = '';
todoList.forEach((todo, index) => {
const todoItem = document.createElement('li');
todoItem.textContent = todo.text;
todoItem.dataset.index = index;
if (todo.completed) {
todoItem.classList.add('done');
}
const completeButton = document.createElement('button');
completeButton.textContent = 'Complete';
completeButton.addEventListener('click', () => {
completeTodoItem(index);
});
todoItem.appendChild(completeButton);
todoListElement.appendChild(todoItem);
});
}
// render completed list
function renderCompletedList() {
const completedListElement = document.getElementById('completed-list');
completedListElement.innerHTML = '';
completedList.forEach((todo, index) => {
const todoItem = document.createElement('li');
todoItem.textContent = todo.text;
todoItem.dataset.index = index;
todoItem.classList.add('done');
completedListElement.appendChild(todoItem);
});
}
// add todo item
function addTodoItem(text) {
const todo = {
text,
completed: false
};
todoList.push(todo);
renderTodoList();
}
// complete todo item
function completeTodoItem(index) {
const todo = todoList.splice(index, 1)[0];
todo.completed = true;
completedList.push(todo);
renderTodoList();
renderCompletedList();
}
// clear task list
function clearTaskList() {
completedList = [];
renderCompletedList();
}
// event listeners
document.getElementById('add-todo-btn').addEventListener('click', (e) => {
e.preventDefault();
const text = document.getElementById('new-todo').value.trim();
if (text) {
addTodoItem(text);
document.getElementById('new-todo').value = '';
}
});
document.getElementById('clear-task-list-btn').addEventListener('click', () => {
clearTaskList();
});
// initial render
renderTodoList();
renderCompletedList();