-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
95 lines (81 loc) · 2.72 KB
/
Copy pathscript.js
File metadata and controls
95 lines (81 loc) · 2.72 KB
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
91
92
93
94
95
// Select DOM Elements
const input = document.getElementById('todo-input')
const addBtn = document.getElementById('add-btn')
const list = document.getElementById('todo-list')
// try to load save todos from localStorage (if any)
const saved = localStorage.getItem('todos');
const todos = saved ? JSON.parse(saved) : [];
function saveTodos() {
// save current todo arry to localStorage
localStorage.setItem('todos', JSON.stringify(todos));
}
// creat a dom node for a todo objectand append it to tha list
function creatTodoNode(todo, index) {
const li = document.createElement('li');
// checkbox to toggle completion
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = !!todo.completed;
checkbox.addEventListener("change", () => {
todo.completed = checkbox.checked;
//visual feedback`: strike-through when completed
textSpan.style.textDecoration = todo.completed ? 'line-through' : "";
saveTodos();
})
// Text of the todo
const textSpan = document.createElement("span");
textSpan.textContent = todo.text;
textSpan.style.margin = '0 8px';
if (todo.completed) {
textSpan.style.textDecoration = 'line-through'
}
// Add double click eventlistener to edit todo
textSpan.addEventListener("dblclick", () => {
const newText = prompt("Edit Todo", todo.text);
if (newText !== null) {
todo.text = newText.trim();
textSpan.textContent = todo.text;
saveTodos();
}
})
// Delete Todo button
const delBtn = document.createElement('button');
delBtn.textContent = "delete";
delBtn.addEventListener('click', () => {
todos.splice(index, 1);
render();
saveTodos();
})
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(delBtn);
return li
}
// Render the whole todo list from todos arry
function render() {
list.innerHTML = '';
// Recreat each items
todos.forEach((todo, index) => {
const node = creatTodoNode(todo, index);
list.appendChild(node)
});
}
function addTodo() {
const text = input.value.trim();
if (!text) {
return
}
// Push a new todo object
todos.push({ text, completed: false });
input.value = '';
render();
saveTodos();
}
addBtn.addEventListener('click', addTodo)// Input field par Enter key ka event lagana
input.addEventListener('keydown', (event) => {
// Check karna ke dabi hui key 'Enter' hi hy
if (event.key === 'Enter') {
addTodo(); // Hamara purana function jo task add karta hy
}
});
render();