-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (52 loc) · 1.62 KB
/
Copy pathscript.js
File metadata and controls
62 lines (52 loc) · 1.62 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
// Grab references to the DOM elements we need
const input = document.getElementById('task-input')
const addBtn = document.getElementById('add-btn')
const list = document.getElementById('task-list')
// Our data: an array of task objects
let tasks = [
{ id: 1, text: 'Read the README', done: false },
{ id: 2, text: 'Open this file in the browser', done: true },
]
// Re-render the whole list from scratch every time data changes
function render() {
list.innerHTML = '' // clear existing DOM
tasks.forEach((task) => {
const li = document.createElement('li')
if (task.done) li.classList.add('done')
const checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.checked = task.done
checkbox.onchange = () => {
task.done = !task.done
render() // <-- have to remember to call this
}
const span = document.createElement('span')
span.className = 'task-text'
span.textContent = task.text
const del = document.createElement('button')
del.className = 'delete-btn'
del.textContent = 'Delete'
del.onclick = () => {
tasks = tasks.filter((t) => t.id !== task.id)
render() // <-- and here
}
li.appendChild(checkbox)
li.appendChild(span)
li.appendChild(del)
list.appendChild(li)
})
}
// Wire up the Add button
addBtn.onclick = () => {
const text = input.value.trim()
if (!text) return
tasks.push({ id: Date.now(), text, done: false })
input.value = ''
render() // <-- and here
}
// Allow Enter key to add too
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') addBtn.click()
})
// Initial render
render()