Want to know how to create a JavaScript To-Do List? In this tutorial, I’ll walk you through this JavaScript project step-by-step.
Whether you’re just starting your web development journey or are keen to learn JavaScript, a JavaScript To-Do List is a fantastic project for beginners to learn real-world JavaScript skills.
In this JavaScript tutorial, you’ll:
- Design an intuitive user interface for a JavaScript To-Do List app.
- Implement functionalities with JavaScript, such as adding, editing, and deleting tasks.
- Dynamically update the To-Do List based on user interactions.
- Handle data persistence by storing tasks in the browser's local storage.
To make the most of this tutorial, it helps to have basic web development skills, including familiarity with HTML and CSS.
Some previous experience with JavaScript, such as manipulating HTML DOM elements and handling events, can also be helpful. However, you don't need to be a JavaScript pro or have prior experience with JavaScript To-Do List apps.
I’ve also provided the full source code for this JavaScript project so you can follow along, experiment, and even build upon it for your own projects.
Plus, you can follow along with me using our online JavaScript compiler, so you don't need an IDE to code this JavaScript project from scratch.
How To Create A JavaScript To-Do List
Are you ready to dive into JavaScript web development with a classic JavaScript project?
Great! Today, we're going to build a JavaScript To-Do List using HTML, CSS, and, of course, JavaScript.
This project is an ideal starting point if you’re new to JavaScript or web development, as it offers a good example of how these three technologies blend to create fun, useful, and interactive web applications.
At the heart of our project, we'll use JavaScript to animate and interact with a static webpage. I always like to think of JavaScript as the brains of the operation, bringing logic and interactivity to the static structure and style of HTML and CSS.
In this simple To-Do List, JavaScript will handle task entries, user interactions, and real-time updates, turning our simple list into a dynamic tool for productivity.
But it's not just about functionality! We'll also make our web app visually appealing and user-friendly. This is where your CSS skills shine, adding style and finesse to our interface.
Take a look at the image I’ve included below to see what you’re going to be building!
Now, you might be wondering, "Is this going to be hard to build?" Absolutely not!
I’ve designed this JavaScript project to be beginner-friendly, and I'll even break it down into manageable, easy-to-follow steps.
So whether you're just starting your journey in web development or have some experience with HTML and CSS but are new to JavaScript, this project is a great way to enhance your skills.
So, let's gear up, switch on our favorite web development IDE, and get ready to create our very own JavaScript To-Do List app.
By the end of this tutorial, not only will you have a practical tool to organize your tasks, but you'll also gain a deeper insight into the synergy between JavaScript, HTML, and CSS in crafting dynamic web experiences.
Let's dive in and create something both functional and fun!
Project Prerequisites
Before we delve into creating our JavaScript To-Do List app, let's review the skills needed to follow along.
And don't worry, you don't need to be a JavaScript wizard to get started, but having a few basics under your belt will make this journey smoother and more enjoyable.
Plus, if you're rusty in any of these areas, you can always brush up with a JavaScript course.
Remember, we’re also here to help, so don’t hesitate to search hackr.io for help as you go along.
HTML Basics
HTML is the skeleton of any web page, comparable to the structure of a building. For this project, familiarity with basic HTML elements such as <div>, <input>, and the overall structure of an HTML document is essential.
If you've ever created a simple webpage or played around with HTML at school or on a web development course, you're good to go!
CSS Essentials
CSS is our tool for styling and beautifying our web pages, akin to the aesthetic touches in building design. For our To-Do List app, basic knowledge of CSS, including styling elements (colors, fonts, and layout properties like margins and padding), is necessary.
If you've experimented with styling web pages before, you have sufficient CSS know-how for this project.
JavaScript Basics
JavaScript brings interactivity and dynamism to our web pages, akin to adding intelligent features to a structure.
You don't need to be a JavaScript wizard, but a grasp of fundamental JavaScript concepts like variables, functions, arrays, and event handling is needed.
If terms like function, event listener, or conditional statements are familiar, you're all set! You can always refer to a JavaScript cheat sheet if you need a quick refresher.
A Curious and Experimental Mindset
Perhaps the most crucial requirement is a curious and experimental approach.
In my opinion, when it comes to JavaScript, the best learning comes from doing, making errors, and iterating. Be prepared to try new things, adjust the code, and sometimes make mistakes (then fix them).
That's the essence of learning and progressing!
You could also consider using an AI coding assistant like GitHub Copilot to help out, but I’d recommend waiting until you’re 100% stuck, as this is where you really learn.
Step 1: Setting Up The Project
Alright! Let's get started by setting up our project. This step is all about laying the groundwork for our JavaScript To-Do List app.
If you want to dive straight in, I'd recommend following along with me using our online JavaScript compiler. This is pre-populated with the HTML, CSS, and JavaScript files you need to build this JavaScript project without switching on an IDE.
Alternatively, I've outlined the steps for you to create the necessary files and organize your workspace on your own computer. Just follow these, and you'll have a solid foundation for your project.
i. Create a Project Folder
First things first, let's keep things tidy. Create a new folder on your computer where you'll store all the files for this project. You can name it something like to-do-list-app.
ii. Initialize Your Files
Inside your project folder, you're going to create three essential files:
- index.html: This will be the main HTML file for your project.
- style.css: This CSS file will hold all your styling rules to make your To-Do List look snazzy.
- script.js: Here's where the magic happens – your JavaScript code goes in this file.
You can create these files using a code editor like VSCode and Sublime Text, or even a text editor like Notepad. Just make sure to save them with the correct extensions.
iii. Link Your CSS and JavaScript Files
Once you've created these files, you need to link them together. Open your index.html file and add the following lines of code inside the <head> tag for the CSS:
<link rel="stylesheet" href="style.css">
And right before the closing </body> tag, add this line for the JavaScript:
<script src="script.js"></script>
These lines tell your HTML file where to find the CSS and JavaScript files and incorporate them into your webpage.
iv. Open Your Project in a Browser
Now, let's see what we've got. Open your index.html file in a web browser.
You won't see much yet – a blank page – but that's about to change. If the page opens without any errors, you're all set!
v. Ready Your Tools
As you work through the next steps, keep your code editor and web browser open side by side. This will allow you to make changes to your code and immediately see the results in the browser.
And there you have it! You've successfully set up your project, and you're ready to dive into the exciting part.
Let's move on to Step 2, where we'll start crafting the HTML structure.
Step 2: Building The To-Do List Structure With HTML
With our project all setup, it's time to focus on the HTML structure of our To-Do List app.
In this step, we'll write the necessary HTML to create a user-friendly interface for task management. Let's dive into the specifics.
i. Start with Basic HTML Structure
Open your index.html file, and let's begin by ensuring the foundational structure of an HTML document is in place. For those who need a quick refresher, here's what it should look like:
<!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 App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- To-Do List will be added here -->
<script src="script.js"></script>
</body>
</html>
This structure is the starting point for all HTML projects, comprising the DOCTYPE declaration, HTML tag, head section (with meta tags, title, and CSS link), and the body for our content.
ii. Adding the To-Do List Components
Inside the <body> tag, we'll create the components for our To-Do List app. Here's a simple way to structure it:
<div id="todo-app">
<h1>My To-Do List</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Add a new task...">
<button type="submit">Add Task</button>
</form>
<ul id="todo-list">
<!-- Tasks will be added here -->
</ul>
</div>
In this layout:
- We have a main container div with the ID todo-app.
- Inside it, there's a heading (<h1>) for our app.
- We include a form (<form>) with an input field for entering new tasks and a submission button.
- Finally, an unordered list (<ul>) with the ID todo-list serves as the area where tasks will be displayed.
iii. Checking Your Work
After saving your changes, open or refresh your web page. You won’t see much styling yet, but you should see the basic elements (heading, input field, and button). This ensures no errors in your HTML so far.
iv. Understanding the HTML Structure
The <div>, <form>, <input>, and <ul> elements are used here to create a structured and interactive interface for the To-Do List app. Each element serves a specific purpose in our app’s functionality and user experience.
v. Tips on HTML Best Practices
While focusing on functionality, remember the importance of clean, well-structured HTML. It's crucial for maintainability and scalability. Commenting your HTML code is also beneficial, especially for larger projects or collaborative work.
And there you have it! You've successfully set up the basic HTML structure for your To-Do List app. This foundation might seem straightforward now, but it's crucial for the dynamic and interactive features we'll add next.
Great job reaching this point – let's continue our momentum into Step 3, where we'll bring our JavaScript To-Do List to life with CSS!
Step 3: Styling the To-Do List With CSS
With our HTML structure for the To-Do List in place, it's time to enhance its visual appeal using CSS.
This step will transform our basic layout into a stylish and user-friendly interface. Let's add some creative flair to our To-Do List!
i. Begin with Basic Styles
Start by opening your style.css file. We'll lay down some foundational styles to ensure our To-Do List looks appealing on any device:
body {
font-family: 'Arial', sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(to right, #6DD5FA, #FF758C);
color: #333;
}
#todo-app {
width: 80%;
max-width: 400px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
Here, we’re:
- Setting a universal font for a clean and consistent look.
- Using Flexbox to center the To-Do List app vertically and horizontally.
- Applying a full viewport height for the body for a full-screen effect.
- Adding a gradient background for a modern and vibrant appearance.
- Defining the style for our main app container with padding, border-radius, and a box-shadow for a polished look.
ii. Style the Input and Button
Next, let's style the input field and the submission button:
#todo-form input[type="text"] {
width: 70%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 4px;
margin-right: 10px;
}
#todo-form button {
padding: 10px 20px;
background-color: #5F9EA0;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
#todo-form button:hover {
background-color: #4682B4;
}
In this section, we’re:
- Styling the input field with padding, border, and border-radius for a clean look.
- Giving the button a distinct color, making it stand out, and ensuring it's clickable.
- Adding a hover effect to the button for better user interaction.
iii. Style the To-Do List
Now, let's style the list of tasks:
#todo-list {
list-style: none;
padding: 0;
}
#todo-list li {
background-color: #f9f9f9;
margin-top: 10px;
padding: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
Here, we’re:
- Removing the default list styling.
- Adding background color, margins, and padding for each list item.
- Using Flexbox to position the content and buttons within each list item.
iv. Save and Refresh
After you’ve added these styles, save your style.css file. Refresh your browser to see the changes. Your To-Do List should now have a defined, interactive appearance.
v. Experiment with Styles
Feel free to personalize the styles. Experiment with colors, fonts, spacing, and more to align with your personal preference or branding.
vi. Responsive Design Consideration
Consider adding responsive design elements to ensure your To-Do List looks good on all devices. For example, use media queries in CSS to adjust styles for different screen sizes.
And that's it! You've successfully styled your JavaScript To-Do List, making it not only functional but visually appealing.
Great work on completing this step. Next, we'll move on to the exciting part of our web development project – adding JavaScript to add interactivity and functionality to our app.
Step 4:JavaScript - Initializing the To-Do List
Now that our To-Do List app looks great, it's time to breathe life into it with JavaScript.
In this step, we'll set up the initial JavaScript code to lay the groundwork for our app's functionality.
We'll focus on initializing variables and setting up event listeners. Let's get our hands on the code!
i. Start with Basic JavaScript Setup
Open your script.js file. We'll begin by declaring variables that we'll use to interact with our HTML elements. Here's how you can start:
const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
In this setup, we’re:
- Selecting the form, input, and list elements from our HTML using their IDs.
- Storing these elements in variables for easy access in our JavaScript code.
ii. Adding Event Listener for Form Submission
We need to handle the event when a user adds a new task. Here’s how you can do it:
todoForm.addEventListener('submit', function(event) {
event.preventDefault();
const newTask = todoInput.value;
if (newTask === '') {
alert('Please enter a task!');
return;
}
// Additional code to add the task will go here
todoInput.value = ''; // Clear the input field after adding a task
});
In this function, we’re:
- Preventing the default form submission behavior, which refreshes the page.
- Checking if the input field is empty and alerting the user if it is.
- Preparing to add the new task (which we will handle in the next steps).
- Clearing the input field after adding a task.
iii. Creating a Function to Add Tasks
Now, let's write a function that will create and display a new task in the list:
function addTask(task) {
const listItem = document.createElement('li');
listItem.textContent = task;
// Additional functionality to be added here
todoList.appendChild(listItem);
}
In this function, we’re:
- Creating a new <li> element for the task.
- Setting its text content to the task passed to the function.
- Appending the new list item to our todo-list element.
iv. Integrating the Add Task Function
Let's integrate our addTask function into the form submission event:
todoForm.addEventListener('submit', function(event) {
// Existing code
addTask(newTask); // Add the new task
});
v. Testing Your Code
After implementing these features, save your script.js file and refresh your browser. Try adding a task using your To-Do List app. You should see the tasks appearing in the list below the input field.
And there we go! You've successfully initialized your JavaScript To-Do List app with basic functionality.
In the next steps, we will enhance our app by adding more interactive features, such as marking tasks as complete and deleting tasks. Keep up the great work!
Step 5: JavaScript - Adding New Tasks
With the initial setup of our To-Do List app complete, it's time to focus on enhancing its functionality.
In this step, we will expand our JavaScript code to handle the addition of new tasks in a more interactive and user-friendly manner. Let’s dive into the code.
i. Enhance the Add Task Function
We need to modify our addTask function to include additional features like checkboxes and delete buttons for each task. Here’s an updated version of the function:
function addTask(task) {
const listItem = document.createElement('li');
const taskText = document.createElement('span');
taskText.textContent = task;
listItem.appendChild(taskText);
const checkBox = document.createElement('input');
checkBox.setAttribute('type', 'checkbox');
listItem.appendChild(checkBox);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
listItem.appendChild(deleteButton);
todoList.appendChild(listItem);
// Event listeners for the checkbox and delete button will be added here
}
In this enhanced function, we’re:
- Creating a span element to hold the task text.
- Adding a checkbox input to each task to mark it as complete.
- Including a delete button to remove tasks.
ii. Implementing Task Completion Feature
We need to handle the task completion functionality. Let’s add an event listener to the checkbox:
checkBox.addEventListener('change', function() {
if (this.checked) {
taskText.style.textDecoration = 'line-through';
} else {
taskText.style.textDecoration = 'none';
}
});
In this section, we’re:
- Adding an event listener to the checkbox.
- Using the change event to toggle the text decoration of the task.
iii. Implementing Task Deletion Feature
Now, let’s add the functionality to delete tasks:
deleteButton.addEventListener('click', function() {
todoList.removeChild(listItem);
});
In this code block, we’re:
- Adding an event listener to the delete button.
- Removing the task from the list when the button is clicked.
iv. Refactor to Improve Code Organization
To keep our code organized and maintainable, let’s refactor the creation of checkboxes and delete buttons into separate functions. You can create functions like createCheckbox and createDeleteButton and call them within addTask.
v. Testing Your Enhanced App
After making these enhancements, save your changes and refresh your browser. Test the new functionalities by adding tasks, marking them as complete, and deleting them. Everything should work smoothly.
You’ve now successfully enhanced your JavaScript To-Do List app, adding essential functionalities and improving user experience.
This step is a crucial part of creating a dynamic and interactive web application. Next, we will continue to build on our app’s functionality, making it even more robust and feature-rich.
Step 6: Implementing Task Editing in JavaScript
At this point, our To-Do List app allows users to add tasks, mark them as complete, and delete them.
Let's add another useful feature: the ability to edit tasks. This step involves creating a function to modify existing tasks, making our To-Do List app more versatile and user-friendly.
i. Adding an Edit Button to Each Task
First, we need to modify our addTask function to include an edit button for each task. Update the function as follows:
function addTask(task) {
// Existing code to create listItem, taskText, checkBox, and deleteButton
const editButton = document.createElement('button');
editButton.textContent = 'Edit';
listItem.appendChild(editButton);
// Event listeners for checkBox and deleteButton
// Add event listener for editButton here
}
In this update, we're:
Creating an editButton and appending it to each listItem.
ii. Implementing the Edit Functionality
Next, let's add the functionality to edit tasks. This involves toggling between viewing and editing states:
editButton.addEventListener('click', function() {
const isEditing = listItem.classList.contains('editing');
if (isEditing) {
// Switch back to view mode
taskText.textContent = this.previousSibling.value; // Assuming the input field is right before the edit button
listItem.classList.remove('editing');
editButton.textContent = 'Edit';
} else {
// Switch to edit mode
const input = document.createElement('input');
input.type = 'text';
input.value = taskText.textContent;
listItem.insertBefore(input, taskText);
listItem.removeChild(taskText);
listItem.classList.add('editing');
editButton.textContent = 'Save';
}
});
In this function, we're:
- Checking if the task is in editing mode.
- If it is, we save the edited task and switch back to view mode.
- If it's not, we switch to edit mode by replacing the task text with an input field.
iii. Refactoring for Clarity and Maintainability
To keep the code clean and maintainable, consider refactoring the edit functionality into a separate function, such as toggleTaskEditState, and call it within the edit button's event listener.
iv. Testing the Edit Feature
Save your script and refresh your browser. Try editing tasks by clicking the edit button, changing the task text, and saving the changes. Ensure that tasks can be toggled between edit and view modes smoothly.
Users can now edit their tasks, making the app more practical and adaptable to their needs.
As you continue to build and refine your app, remember that each feature adds value and improves the user experience.
Up next, we'll explore more ways to enrich our To-Do List app.
Step 7: Saving To Local Storage [Optional]
Our To-Do List app is shaping up nicely with core functionalities like adding, editing, marking as complete, and deleting tasks.
Now, if you feel like stretching yourself, let’s enhance it even further by exploring the possibility of storing tasks in the browser’s local storage.
i. Using Local Storage to Save Tasks
To enhance user experience, let’s save tasks to the browser’s local storage so they persist even after the browser is closed.
1. Saving Tasks to Local Storage:
Modify your task manipulation functions (add, delete, mark complete, edit) to also update the local storage. Here’s an example of how to modify the addTask function:
function saveTasksToLocalStorage() {
const tasks = [];
document.querySelectorAll('#todo-list li').forEach(task => {
const taskText = task.querySelector('span').textContent;
const isCompleted = task.classList.contains('completed');
tasks.push({ text: taskText, completed: isCompleted });
});
localStorage.setItem('tasks', JSON.stringify(tasks));
}
2. Loading Tasks from Local Storage on Page Load:
When the page loads, you should retrieve and display the tasks from local storage:
document.addEventListener('DOMContentLoaded', function() {
const savedTasks = JSON.parse(localStorage.getItem('tasks')) || [];
savedTasks.forEach(task => {
addTask(task.text);
});
});
iii. Testing Enhanced Features
After implementing these features, test your To-Do List app thoroughly:
- Test the local storage feature by adding tasks, refreshing the browser, and ensuring the tasks persist.
If you decided to tackle this section, nice job! You've now significantly enhanced your JavaScript To-Do List app.
These improvements not only provide a better experience for the users but also demonstrate the powerful capabilities of JavaScript in creating dynamic web applications.
Step 8: Final Touches And Testing
Congratulations on reaching the final step of building your JavaScript To-Do List web app!
Now we have all the features in place, it’s time to give our app the last round of polish and ensure everything is working seamlessly.
This step is crucial for enhancing user experience and making sure your app is ready for real-world use.
i. Review and Refine the Code:
- Go through your JavaScript, HTML, and CSS files. Look for any opportunities to simplify or optimize the code.
- Ensure consistent coding style, such as indentation and variable naming conventions.
- Remove any console logs or comments that were used for debugging purposes.
ii. Test All Functionalities:
- Add, edit, delete, and mark tasks as complete to ensure all functionalities are working as expected.
- Test the filter buttons to make sure they correctly display the active, completed, and all tasks.
- Refresh the page to check if tasks persist (assuming you've implemented local storage).
- Try edge cases, like adding empty tasks or very long task descriptions, and ensure your app handles these gracefully.
iii. Ensure Responsive Design:
- Check your app on different devices and screen sizes to ensure it looks good and functions well on all of them.
- Use browser developer tools to simulate various screen sizes and devices.
iv. Improve User Interface and User Experience:
- Ensure that the user interface is intuitive and easy to use.
- Consider adding user-friendly features like showing a confirmation dialog before deleting a task or animations for adding/editing tasks.
- Pay attention to the visual appeal of the app, such as consistent color schemes, readable fonts, and button styles.
v. Browser Compatibility Check:
- Test your app in different browsers like Chrome, Firefox, Safari, and Edge to ensure cross-browser compatibility.
- Resolve any issues that may arise in specific browsers.
vi. Gather Feedback and Iterate:
- If possible, let friends or colleagues use the app and provide feedback.
- Use their insights to make improvements.
vii. Backup and Version Control:
- If you haven’t already, consider using a version control system like Git to keep track of changes and backup your code.
- This practice is essential for any development project, especially when you plan to make future enhancements.
viii. Final Review and Launch:
- Do a final review and walkthrough of your app.
- Once you’re satisfied with everything, your To-Do List Web App is ready to be shared with the world!
Great job on building and refining your To-Do List Web App! This project not only enhances your portfolio but also deepens your understanding of JavaScript, HTML, and CSS in creating functional and dynamic web applications.
Take a moment to appreciate your hard work!
Whether you're building this for fun, as a learning experience, or as a portfolio piece, you've developed valuable skills in programming, problem-solving, and user interface design.
Be proud of your work, share it with others, and consider what project you'll take on next!
Next Steps & Further Learning
Congratulations on successfully building your own interactive JavaScript To-Do List web app!
This is a significant achievement, but your learning journey doesn't stop here. There are many ways to further your skills in web development. Let's explore some ideas:
Learn More About JavaScript and Web Technologies
- JavaScript Enhancements: Explore more advanced JavaScript concepts and apply them to your game. Could features like task filtering based on task state be added?
- Explore Frameworks: Experiment with JS frameworks like React or Vue.js to see how they can be used to build more dynamic and complex web applications.
- Web Animations: Learn about CSS animations and JavaScript to add engaging animations to your To-Do List.
Join Online Communities and Collaborate
- Engage in Forums: Participate in web development forums and communities. Share your To-Do List, get feedback, and learn from others.
- Contribute to Open Source: Consider making your To-Do List app open-source and collaborate with others to improve it.
Keep Up with Trends and Best Practices
Stay updated with the latest trends in web development and JavaScript. Subscribe to blogs like hackr.io, watch webinars, and join online courses.
Document and Share Your Learning Journey
- Blog About Your Project: Write about your development process, challenges you faced, and how you overcame them. Share your blog with the developer community.
- Share Your Code: Publish your code on platforms like GitHub. This not only showcases your work but also allows others to learn from your project.
Challenge Yourself Regularly
Take part in coding challenges or hackathons to sharpen your skills and learn new techniques.
And if you're hungry for more JavaScript projects, check out the rest of our step-by-step tutorials, including:
JavaScript To-Do List App Full Source Code
HTML Source Code:
<!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 App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="todo-app">
<h1>My To-Do List</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Add a new task...">
<button type="submit">Add Task</button>
</form>
<ul id="todo-list">
<!-- Tasks will be added here -->
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
CSS Source Code:
body {
font-family: 'Arial', sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(to right, #6DD5FA, #FF758C);
color: #333;
}
#todo-app {
width: 80%;
max-width: 400px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
#todo-form input[type="text"] {
width: 70%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 4px;
margin-right: 10px;
}
#todo-form button {
padding: 10px 20px;
background-color: #5F9EA0;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
#todo-form button:hover {
background-color: #4682B4;
}
#todo-list {
list-style: none;
padding: 0;
}
#todo-list li {
background-color: #f9f9f9;
margin-top: 10px;
padding: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
JavaScript Source Code:
const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
todoForm.addEventListener('submit', function(event) {
event.preventDefault();
const newTask = todoInput.value;
if (newTask === '') {
alert('Please enter a task!');
return;
}
todoInput.value = '';
addTask(newTask);
});
function addTask(task) {
const listItem = document.createElement('li');
const taskText = document.createElement('span');
taskText.textContent = task;
listItem.appendChild(taskText);
const checkBox = document.createElement('input');
checkBox.setAttribute('type', 'checkbox');
listItem.appendChild(checkBox);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
listItem.appendChild(deleteButton);
todoList.appendChild(listItem);
const editButton = document.createElement('button');
editButton.textContent = 'Edit';
listItem.appendChild(editButton);
checkBox.addEventListener('change', function() {
if (this.checked) {
taskText.style.textDecoration = 'line-through';
} else {
taskText.style.textDecoration = 'none';
}
});
deleteButton.addEventListener('click', function() {
todoList.removeChild(listItem);
});
editButton.addEventListener('click', function() {
const isEditing = listItem.classList.contains('editing');
if (isEditing) {
taskText.textContent = this.previousSibling.value;
listItem.classList.remove('editing');
editButton.textContent = 'Edit';
} else {
const input = document.createElement('input');
input.type = 'text';
input.value = taskText.textContent;
listItem.insertBefore(input, taskText);
listItem.removeChild(taskText);
listItem.classList.add('editing');
editButton.textContent = 'Save';
}
});
saveTasksToLocalStorage();
}
function saveTasksToLocalStorage() {
const tasks = [];
document.querySelectorAll('#todo-list li').forEach(task => {
const taskText = task.querySelector('span').textContent;
const isCompleted = task.classList.contains('completed');
tasks.push({ text: taskText, completed: isCompleted });
});
localStorage.setItem('tasks', JSON.stringify(tasks));
}
document.addEventListener('DOMContentLoaded', function() {
const savedTasks = JSON.parse(localStorage.getItem('tasks')) || [];
savedTasks.forEach(task => {
addTask(task.text);
});
});
Wrapping Up
Building a JavaScript To-Do List using HTML, CSS, and JavaScript is a fantastic way to enhance your web development skills and delve into creating interactive web applications.
By developing this classic app, you've navigated various challenges, including designing a user-friendly interface, implementing task handling logic, and dynamically updating the webpage based on user interactions with their To-Do List items.
In this tutorial, you’ve learned how to:
- Use HTML and CSS to design a clean and user-friendly To-Do List app.
- Write JavaScript to handle task creation, editing, completion, and deletion.
- Dynamically update HTML content with JavaScript to reflect changes in the task list.
- Respond to user inputs by adding event listeners for adding, editing, and filtering tasks.
- Implement persistent storage using local storage to save tasks across browser sessions.
You now have the foundational tools and knowledge you need to further develop and enhance this JavaScript To-Do List. You can add more features, such as due dates, categories for tasks, and notifications, or integrate the To-Do List into a larger productivity tool.
Your journey into the world of JavaScript doesn't end here. With these new skills, you're well-equipped to experiment with more complex JavaScript projects, explore other aspects of JavaScript, and continue building fun and interactive web experiences.
And remember, you can do all this using our online JavaScript compiler, so get creative, have fun, and happy coding!
Want to sharpen up your JavaScript and web development skills? Check out:
Dr. Angela Yu's Complete Web Development Bootcamp