DEV Community

Cover image for Day-4 of Learning JavaScript: Crafting Order out of Chaos: Building an Interactive To-Do List
Aniket Saini
Aniket Saini

Posted on

Day-4 of Learning JavaScript: Crafting Order out of Chaos: Building an Interactive To-Do List

Greetings, fellow developers! Today, we embark on a quest to bring order to the chaos of daily tasks. Join me as we delve into the art of crafting a to-do list — not just any list, but a dynamic, interactive one. Armed with the wizardry of JavaScript, we’ll breathe life into our tasks, allowing users to add, mark as completed, and remove them, all while gracefully updating the DOM.

Chapter 1: The Blank Slate in HTML

Our journey begins with a humble HTML canvas where we’ll structure the foundation of our to-do list.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Magical To-Do List</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to our style sheet -->
</head>
<body>
    <div id="todo-container">
        <!-- The magical form for adding tasks -->
        <form id="todo-form">
            <input type="text" id="task-input" placeholder="Add a new task" required>
            <button type="submit">Add Task</button>
        </form>

        <!-- The enchanted list where tasks come to life -->
        <ul id="task-list">
            <!-- Tasks will be dynamically added here -->
        </ul>
    </div>
    <script src="script.js"></script> <!-- Our JavaScript spellbook -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here’s a breakdown of that code:

Imagine a digital to-do list, neatly organized on your screen. This code creates the basic structure of that list, like a sturdy frame for your tasks.

Here’s how it works:

The Main Container:

  • Think of <div id="todo-container"> as a big box that holds everything together. It's like the main shelf where you'll arrange your to-do list.

The Task Form:

  • Inside that box, you’ll find <form id="todo-form">. This is like a mini-station where you can add new tasks to your list.

It has two parts:

  • The Input Box: <input type="text" id="task-input" placeholder="Add a new task" required> is where you type in the task you want to add. It's like a sticky note you can write on.

  • The Add Button: <button type="submit">Add Task</button> is the button you press to send that task to the list. It's like the "stick it on the shelf" button.

The Task List:

  • <ul id="task-list"></ul> is where your tasks will actually appear, one by one. It's like the bulletin board where you'll see all your tasks lined up.

  • Right now, it’s empty, waiting for you to add some tasks!

So, to sum it up:

  • The code creates a container to hold your to-do list.

  • It sets up a form where you can write down new tasks.

  • It creates a list where those tasks will be displayed.

It’s like setting up the shelves and labels in a store before you start putting items on display. This code is the foundation, ready for JavaScript to come in and make the list interactive and dynamic!

Chapter 2: The Aesthetic Elegance — Styling with CSS

Before we delve into the magical realm of JavaScript, let’s add a touch of style to our to-do list. Open the styles.css file:

/* styles.css */

#todo-container {
  width: 300px;
  margin: 50px auto;
}

#todo-form {
  display: flex;
  margin-bottom: 20px;
}

#task-input {
  flex-grow: 1;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px 0 0 5px;
}

button {
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 0 5px 5px 0;
  cursor: pointer;
}

#task-list {
  list-style: none;
  padding: 0;
}

.task {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.task input {
  margin-right: 10px;
}

.task span {
  max-width: 70%;
  overflow: hidden;
}

.task button {
  margin-left: 10px;
  background-color: tomato;
  border: none;
  border-radius: 10px;
}

.task button:hover {
  background-color: red;
  transition: 0.5s ease-in-out;
}

.completed span {
  color: red;
  text-decoration: line-through;
}
Enter fullscreen mode Exit fullscreen mode

Our CSS spell adds a touch of flair. The form and buttons get a stylish makeover, and each task in the list becomes a visually appealing entity — ready to dance into your to-do day!

Chapter 3: The JavaScript Alchemy

Now, brace yourself as we infuse life into our to-do list using the magic of JavaScript. Open the script.js file and let the spells begin:

// script.js

// Our magical spellbook begins

const todoForm = document.getElementById("todo-form"); // The form
const taskInput = document.getElementById("task-input"); // The task input
const taskList = document.getElementById("task-list"); // The task list

// Event listener for form submission
todoForm.addEventListener("submit", function (event) {
  event.preventDefault(); // Prevents the default form submission behavior

  const taskText = taskInput.value; // Fetching the task text

  if (taskText.trim() !== "") {
    // Checking if the task is not empty
    addTask(taskText); // Adding the task to the list
    taskInput.value = ""; // Clearing the input field
  }
});

// Function to add a task to the list
function addTask(taskText) {
  const taskItem = document.createElement("li"); // Creating a new list item
  taskItem.className = "task"; // Adding the 'task' class

  const taskCheckbox = document.createElement("input"); // Creating a checkbox
  taskCheckbox.type = "checkbox"; // Setting the type to checkbox
  taskCheckbox.addEventListener("change", function () {
    toggleTaskCompletion(taskItem); // Toggling the task completion status
  });

  const taskTextElement = document.createElement("span"); // Creating a span for the task text
  taskTextElement.textContent = taskText; // Setting the text content

  const deleteButton = document.createElement("button"); // Creating a delete button
  deleteButton.textContent = "Delete"; // Setting the button text
  deleteButton.addEventListener("click", function () {
    removeTask(taskItem); // Removing the task from the list
  });

  // Appending elements to the task item
  taskItem.appendChild(taskCheckbox);
  taskItem.appendChild(taskTextElement);
  taskItem.appendChild(deleteButton);

  // Appending the task item to the task list
  taskList.appendChild(taskItem);
}

// Function to toggle the completion status of a task
function toggleTaskCompletion(taskItem) {
  taskItem.classList.toggle("completed"); // Toggling the 'completed' class

  // Check if the task is now completed
  const isCompleted = taskItem.classList.contains("completed");

  // Update text style based on completion status
  const taskTextElement = taskItem.querySelector("span");
  if (isCompleted) {
    taskTextElement.style.color = "red";
    taskTextElement.style.textDecoration = "line-through";
  } else {
    // Reset styles if the task is not completed
    taskTextElement.style.color = "";
    taskTextElement.style.textDecoration = "";
  }
}

// Function to remove a task from the list
function removeTask(taskItem) {
  taskList.removeChild(taskItem); // Removing the task item from the list
}
Enter fullscreen mode Exit fullscreen mode

Here’s a breakdown of the code, just like we’re chatting over coffee:

Gathering the Tools:

  • Imagine the code as a handyman, first grabbing its essential tools:

  • todoForm: This is the form you use to add new tasks.

  • taskInput: This is the box where you type in your task.

  • taskList: This is the list where all your tasks will be displayed.

Listening for New Tasks todoForm.addEventListener('submit', function (event) { ... });:

  • The handyman’s ear is always open! It’s listening for when you submit the form:

  • If you write something in the taskInput and hit submit...

  • The handyman jumps into action to create a new task item.

Crafting a Task Item addTask(taskText):

  • Imagine the handyman building a new task item like a mini-house:

  • It starts with a foundation (li), the basic structure of the item.

  • It adds a checkbox (input), so you can mark a task as done.

  • It puts up a sign (span) to display the task text you wrote.

  • It adds a fancy doorknob (button), which acts as a delete button.

  • It carefully places the checkbox and text inside the house, and attaches the doorknob.

  • Finally, it proudly puts the finished house (task item) onto the main street (task list).

Checking Off Tasks toggleTaskCompletion(taskItem):

  • When you click a checkbox, the handyman knows it’s time to mark a task as done:

  • It paints the task text red and adds a strikethrough, like a big checkmark.

Removing Completed Tasks removeTask(taskItem):

  • If you decide a task is no longer needed, the handyman is ready to demolish:

  • When you click the delete button, it carefully removes the task item from the list.

  • In essence, this code acts like a diligent task manager, always ready to create, update, and remove tasks based on your instructions!

Here are the key JavaScript concepts demonstrated in this project:

DOM Manipulation:

  • Selecting elements: The code uses document.getElementById to retrieve specific elements from the HTML document, such as the form, input field, and task list.

  • Creating elements: It creates new elements dynamically using document.createElement to construct list items, checkboxes, text elements, and buttons.

  • Appending elements: It adds these newly created elements to the task list using appendChild, building the to-do list structure.

  • Modifying elements: It toggles the “completed” class on task items using classList.toggle to visually indicate completion.

  • Removing elements: It removes task items from the list using removeChild when the delete button is clicked.

Event Listeners:

  • Attaching listeners: The code uses addEventListener to listen for specific events on elements:

  • submit event on the form to capture new task submissions.

  • change event on checkboxes to handle task completion toggling.

  • click event on delete buttons to remove tasks.

  • Preventing default behavior: It prevents the form from submitting normally using event.preventDefault.

Working with User Input:

  • Retrieving input: It captures the text entered by the user in the task input field using taskInput.value.

  • Validating input: It checks if the input is empty using taskText.trim() !== """ before adding a new task.

Function Definitions:

  • Organizing code: The code is structured into reusable functions for adding tasks, toggling task completion, and removing tasks, making it more modular and readable.

Conditional Logic:

  • Controlling flow: The code uses conditional statements (if/else) to determine when to add tasks (based on valid input) and to apply visual styles for completed tasks.

The Grand Finale

Open your enchanted HTML page in a browser and behold the magic! Add tasks, mark them as completed with checkboxes, and banish them from the list with the delete button. Our to-do list, crafted with HTML and animated by JavaScript, is now ready to bring order to your chaotic day. Embrace the magic, dear apprentice!

CLICK HERE to check final Output

Epilogue: The Power of Interactivity

As you traverse the realms of web development, remember that every line of code is a spell, capable of conjuring unique digital experiences. Our humble to-do list, a fusion of HTML, CSS, and JavaScript, is a testament to the power of interactivity in web development.

May you continue to explore, experiment, and weave your own magic in the wondrous world of web development. Happy coding, and may your to-do lists be forever organized! Now, go forth and conquer your tasks with the

Top comments (0)