-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathTo-Do List with Local Storage
91 lines (91 loc) · 2.51 KB
/
To-Do List with Local Storage
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
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List with Local Storage</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="todo-container">
<h1>To-Do List</h1>
<form id="todoForm">
<input type="text" id="taskInput" placeholder="Enter a new task" required>
<button type="submit">Add Task</button>
</form>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.todo-container {
text-align: center;
background-color: #f0f0f0;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
margin: 5px 0;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
display: flex;
justify-content: space-between;
}
button.remove {
background: none;
border: none;
color: red;
cursor: pointer;
font-size: 16px;
}
JavaScript:
document.addEventListener('DOMContentLoaded', function() {
const taskList = document.getElementById('taskList');
const tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks.forEach(task => {
addTaskToDOM(task);
});
document.getElementById('todoForm').addEventListener('submit', function(event) {
event.preventDefault();
const taskInput = document.getElementById('taskInput');
const taskText = taskInput.value;
if (taskText === '') return;
addTaskToDOM(taskText);
tasks.push(taskText);
localStorage.setItem('tasks', JSON.stringify(tasks));
taskInput.value = '';
});
function addTaskToDOM(taskText) {
const li = document.createElement('li');
li.textContent = taskText;
const removeButton = document.createElement('button');
removeButton.textContent = 'Remove';
removeButton.classList.add('remove');
removeButton.addEventListener('click', function() {
li.remove();
const index = tasks.indexOf(taskText);
tasks.splice(index, 1);
localStorage.setItem('tasks', JSON.stringify(tasks));
});
li.appendChild(removeButton);
taskList.appendChild(li);
}
});