Let’s Build a Simple To-Do List!
Project Goal: Create a web application where users can add, edit, and remove tasks from a list.
Step 1: Set up the HTML Structure
Create an HTML file (e.g., index.html
) with the following basic structure:
HTML
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<ul id="taskList"></ul>
<input type="text" id="taskInput" placeholder="Enter a task">
<button id="addTaskButton">Add Task</button>
</body>
</html>
Step 2: Add JavaScript Functionality
Create a JavaScript file (e.g., script.js
) and link it to your HTML file:
HTML
<script src="script.js"></script>
In your JavaScript file, add the following code:
JavaScript
const taskInput = document.getElementById('taskInput');
const addTaskButton = document.getElementById('addTaskButton');
const taskList = document.getElementById('taskList');
addTaskButton.addEventListener('click', () => {
const taskText = taskInput.value;
if (taskText !== '') {
const listItem = document.createElement('li');
listItem.textContent = taskText;
taskList.appendChild(listItem);
taskInput.value = '';
}
});
Explanation:
- Select elements: We select the input field, button, and list element using their IDs.
- Add event listener: We add a click event listener to the button.
- Create list item: When the button is clicked, we create a new list item element.
- Add task text: We set the text content of the list item to the value of the input field.
- Append to list: We append the new list item to the task list.
- Clear input: We clear the input field for the next task.
Run the Project
- Open your HTML file in a web browser.
- Enter a task in the input field and click the “Add Task” button.
- The task will be added to the list.
Next Steps:
- Add a delete button: Create a delete button for each list item and implement the functionality to remove the item when clicked.
- Implement editing: Allow users to edit existing tasks by creating an edit button and enabling them to modify the task text.
- Store data: Use local storage or a database to persist the to-do list data, even after the page is refreshed.
This is a basic foundation for your to-do list application. You can further enhance it with features like task completion, sorting, and filtering.