-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathscript.js
More file actions
57 lines (47 loc) · 1.58 KB
/
script.js
File metadata and controls
57 lines (47 loc) · 1.58 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
// Get DOM elements
const taskInput = document.getElementById('task-input');
const addButton = document.getElementById('add-button');
const taskList = document.getElementById('task-list');
// --- INITIAL LOAD ---
// Load tasks from Local Storage when the page loads
document.addEventListener('DOMContentLoaded', loadTasks);
// --- EVENT LISTENERS ---
addButton.addEventListener('click', addTask);
taskInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
addTask();
}
});
taskList.addEventListener('click', handleTaskActions); // Single listener for all list item clicks
// --- CORE FUNCTIONS ---
/* Handles clicks on the task list container.
* This is more efficient than adding listeners to every task item.
*/
function handleTaskActions(e) {
const target = e.target;
const listItem = target.closest('li'); // Find the nearest parent <li>
if (!listItem) return; // If clicked outside an <li>
if (target.classList.contains('delete-btn')) {
// Handle Delete Button Click
listItem.remove();
saveTasks();
} else {
// Handle Task Text Click (Toggle Complete)
listItem.classList.toggle('completed');
saveTasks();
}
}
/* Creates and appends a new task item to the list.
*/
function addTask() {
const taskText = taskInput.value.trim();
if (taskText === "") {
alert("Please enter a task!");
return;
}
// Call the function to create the actual task element
createTaskElement(taskText, false);
// Clear input and save
taskInput.value = '';
saveTasks();
}