JavaScript - Building a To-Do List Application

Building a To-Do List Application using JavaScript

A to-do list application is a straightforward yet useful project that shows how to use fundamental web development techniques, such as JavaScript for functionality, HTML for structure, and CSS for design. Users can add, remove, and mark tasks as done in an interactive manner to manage their work.

Project Overview

With this app, users will be able to:

  • Create a list of new tasks.
  • Check off tasks to indicate that you have finished them.
  • Take the tasks from the list.
  • Use local storage to keep jobs going between sessions.

 

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple To-Do List</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>My To-Do List</h1>
    <input id="newTask" type="text" placeholder="Add a new task">
    <button onclick="addTask()">Add Task</button>
    <ul id="tasksList"></ul>
    <script src="script.js"></script>
</body>
</html>

The title, the input form for new tasks, the button to add tasks, and the unordered list to show the tasks are all provided by the HTML.

CSS (style.css)

body {
    font-family: Arial, sans-serif;
    padding: 20px;
    background-color: #f4f4f4;
}

h1 {
    color: #333;
}

#newTask {
    padding: 10px;
    width: 300px;
    margin-right: 10px;
}

button {
    padding: 10px 20px;
    cursor: pointer;
}

ul {
    list-style: none;
    padding: 0;
}

li {
    background-color: #fff;
    padding: 10px;
    margin-top: 10px;
    border-radius: 5px;
}

input[type="checkbox"] {
    margin-right: 10px;
}

To make the to-do list more aesthetically pleasing and user-friendly, this CSS adds some basic style.

JavaScript (script.js)

document.getElementById('newTask').addEventListener('keypress', function(event) {
    if (event.key === 'Enter') {
        addTask();
    }
});

function addTask() {
    const taskInput = document.getElementById('newTask');
    const task = taskInput.value.trim();
    if (task === '') return;

    const li = document.createElement('li');
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.addEventListener('change', function() {
        if (this.checked) {
            li.style.textDecoration = 'line-through';
        } else {
            li.style.textDecoration = 'none';
        }
    });

    li.appendChild(checkbox);
    li.append(task);
    document.getElementById('tasksList').appendChild(li);
    taskInput.value = ''; // Clear input field

    saveTasks();
}

function saveTasks() {
    const tasks = [];
    document.querySelectorAll('#tasksList li').forEach(li => {
        tasks.push({
            text: li.textContent,
            completed: li.firstChild.checked
        });
    });
    localStorage.setItem('tasks', JSON.stringify(tasks));
}

function loadTasks() {
    const tasks = JSON.parse(localStorage.getItem('tasks'));
    if (!tasks) return;
    tasks.forEach(task => {
        const li = document.createElement('li');
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.checked = task.completed;
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                li.style.textDecoration = 'line-through';
            } else {
                li.style.textDecoration = 'none';
            }
        });

        li.appendChild(checkbox);
        li.append(task.text);
        document.getElementById('tasksList').appendChild(li);
    });
}

window.onload = loadTasks;

JavaScript enhances the application by enabling features such, as task addition completion marking and local storage management.

Each time a new task is added it is stored in storage to maintain data persistence between sessions.

Upon page load, the application retrieves tasks, from storage to restore the tasks from the session.

This basic to-do list app showcases web development principles. Illustrates how HTML, CSS, and JavaScript collaborate to build engaging web experiences.

logo

JavaScript

Beginner 5 Hours

Building a To-Do List Application using JavaScript

A to-do list application is a straightforward yet useful project that shows how to use fundamental web development techniques, such as JavaScript for functionality, HTML for structure, and CSS for design. Users can add, remove, and mark tasks as done in an interactive manner to manage their work.

Project Overview

With this app, users will be able to:

  • Create a list of new tasks.
  • Check off tasks to indicate that you have finished them.
  • Take the tasks from the list.
  • Use local storage to keep jobs going between sessions.

 

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple To-Do List</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>My To-Do List</h1>
    <input id="newTask" type="text" placeholder="Add a new task">
    <button onclick="addTask()">Add Task</button>
    <ul id="tasksList"></ul>
    <script src="script.js"></script>
</body>
</html>

The title, the input form for new tasks, the button to add tasks, and the unordered list to show the tasks are all provided by the HTML.

CSS (style.css)

body {
    font-family: Arial, sans-serif;
    padding: 20px;
    background-color: #f4f4f4;
}

h1 {
    color: #333;
}

#newTask {
    padding: 10px;
    width: 300px;
    margin-right: 10px;
}

button {
    padding: 10px 20px;
    cursor: pointer;
}

ul {
    list-style: none;
    padding: 0;
}

li {
    background-color: #fff;
    padding: 10px;
    margin-top: 10px;
    border-radius: 5px;
}

input[type="checkbox"] {
    margin-right: 10px;
}

To make the to-do list more aesthetically pleasing and user-friendly, this CSS adds some basic style.

JavaScript (script.js)

document.getElementById('newTask').addEventListener('keypress', function(event) {
    if (event.key === 'Enter') {
        addTask();
    }
});

function addTask() {
    const taskInput = document.getElementById('newTask');
    const task = taskInput.value.trim();
    if (task === '') return;

    const li = document.createElement('li');
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.addEventListener('change', function() {
        if (this.checked) {
            li.style.textDecoration = 'line-through';
        } else {
            li.style.textDecoration = 'none';
        }
    });

    li.appendChild(checkbox);
    li.append(task);
    document.getElementById('tasksList').appendChild(li);
    taskInput.value = ''; // Clear input field

    saveTasks();
}

function saveTasks() {
    const tasks = [];
    document.querySelectorAll('#tasksList li').forEach(li => {
        tasks.push({
            text: li.textContent,
            completed: li.firstChild.checked
        });
    });
    localStorage.setItem('tasks', JSON.stringify(tasks));
}

function loadTasks() {
    const tasks = JSON.parse(localStorage.getItem('tasks'));
    if (!tasks) return;
    tasks.forEach(task => {
        const li = document.createElement('li');
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.checked = task.completed;
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                li.style.textDecoration = 'line-through';
            } else {
                li.style.textDecoration = 'none';
            }
        });

        li.appendChild(checkbox);
        li.append(task.text);
        document.getElementById('tasksList').appendChild(li);
    });
}

window.onload = loadTasks;

JavaScript enhances the application by enabling features such, as task addition completion marking and local storage management.

Each time a new task is added it is stored in storage to maintain data persistence between sessions.

Upon page load, the application retrieves tasks, from storage to restore the tasks from the session.

This basic to-do list app showcases web development principles. Illustrates how HTML, CSS, and JavaScript collaborate to build engaging web experiences.

Related Tutorials

Frequently Asked Questions for JavaScript

JavaScript is a high-level, interpreted programming language primarily used for creating interactive and dynamic content on web pages. It enables developers to implement complex features such as real-time updates, interactive forms, and animations.

In JavaScript:

Synchronous programming executes code sequentially, blocking subsequent operations until the current one completes.
Asynchronous programming allows code to execute **non-sequentially

You can debug JavaScript using browser developer tools, the **console.log()** method, and breakpoints in Chrome/Firefox. Tools like VSCode, Chrome DevTools, and debuggers help trace and fix issues.

A JavaScript array is a special variable that can hold multiple values. Common methods include .push(), .pop(), .shift(), .unshift(), .map(), .filter(), and .reduce().

A promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

In JavaScript DOM events, event bubbling means the event propagates from the target element up to the root. Event capturing is the opposite, where the event travels from root to target.

In JavaScript:

**setTimeout()** executes a function once after a specified delay.
**setInterval()** executes a function repeatedly, with a fixed time delay between each call.

Event delegation is a technique in JavaScript where a parent element handles events for its child elements, utilizing the concept of event bubbling to manage events more efficiently.

The **this** keyword in JavaScript refers to the object from which it was called. Its value changes depending on the execution context (e.g., in a method, constructor, or global scope).

Both are part of the Web Storage API in JavaScript:

**localStorage** stores data with no expiration time.
**sessionStorage** stores data for the duration of the page session.

A shallow copy duplicates only the first level of an object, while a deep copy duplicates all nested levels, ensuring that modifying the copy doesn’t affect the original.

Prototypal inheritance allows JavaScript objects to inherit properties and methods from other objects using the prototype chain, enabling code reuse and OOP (Object-Oriented Programming) patterns.

An arrow function (=>) is a shorter syntax for writing functions in JavaScript. It does not bind its own this, making it ideal for callbacks and functional programming.

All three methods are used to change the context of **this** in JavaScript functions:

**call()** invokes a function with arguments individually.
**apply()** accepts arguments as an array.
**bind()** returns a new function with a fixed **this** context.

Template literals (using backticks `) in JavaScript allow for string interpolation, multi-line strings, and embedded expressions using ${} syntax.

The DOM is a programming interface for HTML and XML documents. It represents the document as a tree of nodes, allowing JavaScript to manipulate the content and structure of web pages dynamically.

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase, allowing code to use functions and variables before they are declared.

In JavaScript, a function is a block of code designed to perform a particular task. Functions are executed when they are invoked (called).

In JavaScript:

Function Declarations: Defined with the function keyword followed by the function name and are hoisted, meaning they can be called before their declaration in the code.​
Function Expressions: Defined by assigning a function to a variable and are not hoisted, so they cannot be called before their definition.

The **isNaN()** function in JavaScript determines whether a value is NaN (Not-a-Number). It returns true if the value is NaN, and false otherwise.

A closure in JavaScript is a function that retains access to its lexical scope, even when the function is executed outside that scope. This allows functions to maintain access to variables from their containing function.

In JavaScript:

var is function-scoped and can be redeclared and reassigned.​
let is block-scoped and can be reassigned but not redeclared in the same scope.​
const is block-scoped, cannot be reassigned, and must be initialized during declaration.

In JavaScript:

**null** is an assignment value that represents no value or no object.
**undefined** means a variable has been declared but has not yet been assigned a value.

In JavaScript:

== performs loose equality comparison, converting operands to the same type before comparison.​
=== performs strict equality comparison, considering both value and type.

JavaScript supports various data types, including:

Primitive Types: Number, String, Boolean, Undefined, Null, Symbol, BigInt.​
Reference Types: Object, Array, Function. 

line

Copyrights © 2024 letsupdateskills All rights reserved