Lecture Notes Of Day 30:
JavaScript Project
Objective:
- Apply
everything you've learned in the JavaScript course by building a small,
practical project.
- In
this session, students will apply concepts such as DOM
manipulation, event handling, local storage, functions,
and arrays to create a To-Do List application.
Introduction to the Project
Today, you will build a
simple To-Do List application using JavaScript.
This will help you to consolidate the skills you've acquired throughout this
course. The application will allow users to:
- Add
tasks to the list.
- Edit
existing tasks.
- Delete
tasks.
- Mark
tasks as completed.
- Store
tasks in the local storage so that they persist even when
the page is refreshed.
Project Breakdown
1. Create the HTML Structure
Start by building the
basic structure of the application with HTML. This will involve creating
elements that users will interact with.
HTML Structure:
|
<html
lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>To-Do List Application</title>
<link rel="stylesheet" href="style.css"> </head> <body>
<div class="container">
<h1>My To-Do List</h1>
<input type="text" id="task-input"
placeholder="Add a new task">
<button id="add-task">Add Task</button>
<ul id="task-list"></ul>
</div>
<script src="script.js"></script> </body> </html>
|
In this structure:
- The input
field is where users will type the task.
- The button allows
users to add tasks to the list.
- The ul element
is where the tasks will be displayed.
2. Add Styling with CSS
Style your application to
make it visually appealing. You can use CSS to align the
elements and set background colors.
CSS (style.css):
|
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
margin: 0; } .container {
text-align: center;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 300px; } input {
padding: 10px;
width: 70%;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px; } button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer; } button:hover {
background-color: #45a049; } ul {
list-style-type: none;
padding: 0; } li {
padding: 10px;
margin: 5px 0;
background-color: #e0e0e0;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center; } li.completed {
text-decoration: line-through;
background-color: #d0ffd0; } button.delete-btn {
background-color: red;
padding: 5px;
border-radius: 4px;
cursor: pointer; } button.delete-btn:hover
{
background-color: darkred; }
|
This CSS file will style
the page to make it look clean and professional. It includes styling for the
input box, buttons, and the task list items.
3. Add Functionality with JavaScript
Now, let’s implement
the JavaScript to add interactivity to the To-Do List. We will
handle task addition, task deletion, task
editing, and task completion using JavaScript.
JavaScript (script.js):
|
// Get elements const taskInput =
document.getElementById("task-input"); const addTaskButton =
document.getElementById("add-task"); const taskList =
document.getElementById("task-list"); // Load tasks from
local storage let tasks =
JSON.parse(localStorage.getItem("tasks")) || []; // Function to render
tasks function renderTasks()
{
taskList.innerHTML = ""; // Clear the list before re-rendering
tasks.forEach((task, index) => {
const li = document.createElement("li");
li.classList.toggle("completed", task.completed);
const taskText = document.createElement("span");
taskText.textContent = task.text;
taskText.addEventListener("click", () => toggleComplete(index));
const deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.classList.add("delete-btn");
deleteButton.addEventListener("click", () => deleteTask(index));
li.appendChild(taskText);
li.appendChild(deleteButton);
taskList.appendChild(li); }); } // Function to add a
new task function addTask() {
const taskText = taskInput.value.trim(); if
(taskText) {
tasks.push({ text: taskText, completed: false });
taskInput.value = "";
saveTasks();
renderTasks(); } } // Function to toggle
task completion function
toggleComplete(index) {
tasks[index].completed = !tasks[index].completed;
saveTasks();
renderTasks(); } // Function to delete a
task function
deleteTask(index) {
tasks.splice(index, 1);
saveTasks();
renderTasks(); } // Function to save
tasks to local storage function saveTasks() {
localStorage.setItem("tasks", JSON.stringify(tasks)); } // Event listeners addTaskButton.addEventListener("click",
addTask); taskInput.addEventListener("keypress",
(e) => { if
(e.key === "Enter") addTask(); }); // Initial render renderTasks();
|
Explanation of Code:
1. Selecting
DOM Elements:
o We
select the input field (task-input), the button (add-task), and the task list
(task-list) to manipulate them later.
2. Tasks
Array:
o An
array tasks is created to store all the tasks. It is initially populated
from local storage if any tasks exist from a previous session.
3. Rendering
Tasks:
o The
renderTasks() function renders each task in the tasks array as a list item
(<li>) on the page. It creates a span for the task text and a delete
button for each task.
4. Adding
a Task:
o The
addTask() function adds a new task to the tasks array when the "Add
Task" button is clicked or when the user presses "Enter".
5. Toggling
Completion:
o The
toggleComplete() function toggles the completed state of a task when its text
is clicked. It applies or removes the .completed class to strike through the
text.
6. Deleting
a Task:
o The
deleteTask() function removes a task from the array when the delete button is
clicked.
7. Saving
Tasks:
o The
saveTasks() function saves the tasks array to local storage so
the tasks persist even when the page is refreshed.
8. Event
Listeners:
o Event
listeners are used to trigger the appropriate functions for adding tasks,
toggling completion, and deleting tasks.
Project Walkthrough:
1. When
the page is loaded, the tasks are fetched from the browser's local
storage using localStorage.getItem(), and rendered on the screen.
2. Adding
a task: When the user types a task and clicks the "Add Task"
button or presses "Enter", the task is added to the tasks array. The
array is then saved to local storage, and the tasks are re-rendered
on the page.
3. Marking
a task as completed: Clicking on the task will toggle its completion
status. The text of the task will be struck-through when marked as completed.
4. Deleting
a task: Clicking the "Delete" button next to a task will remove
that task from the tasks array and update the UI.
Conclusion:
- By
building this To-Do List project, you have learned how to apply core
JavaScript concepts such as DOM manipulation, event
handling, local storage, and functions.
- This
project demonstrates how to interact with the browser, store data
persistently, and update the user interface dynamically.
Next Steps:
- Improve
the UI: You can style the task list further
by adding colors, hover effects, and better layouts.
- Add
more features: Think about adding features like
task priorities, deadlines, or categorization.
- Deploy
your project: Once your project is complete,
consider deploying it to a platform like GitHub Pages.
This project serves as an
excellent foundation for building more complex applications as you continue
learning JavaScript.
