Build a Crud application with JavaScript
In this tutorial, we will be looking at how we can create a Crud application with JavaScript. In the course of this article, we will create a Todo app. It is focused more on beginners learning javascript.
A todo app is the most popular thing to build when learning a new programming language, and all you need is a basic knowledge of javascript.
Take a sneak peek at the application we are going to build:
You must know what Variables, Arrays, Function, and Objects are before proceeding with the tutorial.
In the course of this tutorial, we will be looking at how user can:
- Add a task
- Mark a task as completed
- Delete an already added task
Creating UI
We will start by building the UI for the app.
We are going to start by creating a .html
file where all the Html code will be written.
<!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</title>
<link rel="stylesheet" href="index.css" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div class="container">
<div class="todo">
<h1>Todo</h1>
<p>What do you want to get done today?</p>
<form id="form">
<input type="text" id="input" placeholder="Enter task" />
</form>
</div>
<div class="list-todo">
<ul id="todo"></ul>
</div>
</div>
http://index.js
</body>
</html>
In the above code is a html meta tag
and a div with a class="container"
. Inside the div, we have a form tag and a ul tag.
The form tag has an input element. the input element has an Id=”input” which we are going to use to get the value as user types.
The ul tag is where we are going to display the value after the user hit the enter button.
We are going to style the Html tag to make our todo app look good. Create a .css
file and link it inside the meta tag.
html,
body {
margin: 0;
padding: 0;
font-family: "Roboto", sans-serif;
--text-color: #333;
color: var(--text-color);
background-color: #e0f0fd;
}
.container {
text-align: center;
width: 40%;
margin: auto;
color: #181818;
min-height: 90vh;
margin-top: 2%;
}
.todo {
width: 100%;
padding-bottom: 15px;
background: #3366ff;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
color: #ffffff;
}
h1 {
margin-bottom: 20px;
font-size: 80px;
margin-top: 0;
padding-left: 10px;
}
input {
background: none;
outline: none;
border: none;
border-bottom: 2px solid #ffffff;
color: #ffffff;
padding: 8px;
font-size: 20px;
}
.list-todo {
height: 60vh;
background-color: #ffffff;
overflow-x: scroll;
}
#todo {
padding: 0 10px 0 10px;
}
#todo li {
list-style: none;
font-size: 16px;
width: 100%;
max-width: 100%;
display: flex;
--webkit-display: flex;
align-items: flex-start;
justify-content: space-between;
text-align: justify;
margin-bottom: 15px;
border-bottom: 1px solid #777777;
padding-bottom: 8px;
}
#todo li.completed {
text-decoration: line-through;
}
#todo li.uncompleted {
text-decoration: none;
color: black;
}
#todo li input {
margin-right: 10px;
}
#todo li button {
outline: none;
border: none;
border-radius: 200px;
margin-left: 10px;
background-color: #3366ff;
color: #ffffff;
width: 6%;
height: 5vh;
}
Add a task
Now we are going to create a .js file
and link it inside the body of the Html.
The .js file we created is where we are going to write the code that will trigger the input tag to submit a value whenever a user adds a task.
const form = document.getElementById("form");
const input = document.getElementById("input");
const button = document.getElementById("button");
const todo = document.getElementById("todo");
let todoList = [];
form.addEventListener("submit", function (e) {
e.preventDefault();
addTodo();
});
function addTodo() {
// get input
const newTodo = input.value;
// return if nothing was entered
if (!newTodo) return;
// add the new task to todo list
todoList.push({
text: newTodo,
completed: false,
});
// add the todo list to localstorage
localStorage.setItem("todos", JSON.stringify(todoList));
// render todo list
render();
}
In the above code, we declared a global constant variable which means that the variables can be used anywhere inside the .js file. And document.getElementById is a DOM method used to return the element that has an ID attribute. You can see that all the variables we created are set to have the value of these specific elements and If we notice, our Input tag has an Id attribute “input” and to get that input in order to access the value, we have to use document.getElementById but if it was a class we would have used document.querrySelector.
The form.addEventListener
submits the value after the user adds a task and click enter.
The e.preventDefault prevents the page from reloading when the user click enter and we called a function addTodo() whenever user adds a task.
We created a function addTodo()
that we call each time a user adds a task. In the function, we declared a constant variable newTodo that is assigned the value of the input.value
. This variable can only be accessed within the function because it is a local variable.
We also have a conditional statement that runs if there is no value inputted when the user clicks the enter key but if there is a value inputted we push it to the empty array we declared before rendering it to the DOM.
We store the array in the localStorage so that we can still access the value anytime.
Mark a task as completed
function render() {
// clear the list
todo.innerHTML = null;
// get the todo list from localstorage
const todos = localStorage.getItem("todos");
todoList = JSON.parse(todos) || [];
for (let i = 0; i < todoList.length; i++) {
const item = document.createElement("li");
// create checkbox to update completed state
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.addEventListener("click", function (e) {
todoList[i].completed = e.target.checked;
localStorage.setItem("todos", JSON.stringify(todoList));
// check if todo item is completed and add appropriate class
if (todoList[i].completed) {
item.classList.add("completed");
item.classList.remove("uncompleted");
checkbox.checked = todoList[i].completed;
} else {
item.classList.add("uncompleted");
item.classList.remove("completed");
checkbox.checked = todoList[i].completed;
}
});
}
}
We created another function render()
. In the render()
function, we first cleared the input tag after the user adds a task.
We also fetch the value we stored in the localStorage and loop through the value.
Created li tag
, Input tag, and set the input type to be checkbox.
To check if the checkbox is checked, we added an event listener that fire when the checkbox is been checked and unchecked.
The checked input type return boolean as a value, when checked it returns True but when unchecked it returns false and we stored the value in the localStorage.
The if(){}
condition runs when a user checks the checkbox or unchecks the checkbox.
Delete an already added task
// create text node
const text = document.createElement("p");
text.innerText = todoList[i].text;
// create delete button
const button = document.createElement("button");
button.innerText = "X";
button.addEventListener("click", function () {
todoList.splice(i, 1);
localStorage.setItem("todos", JSON.stringify(todoList));
render();
});
Still, inside the render()
function, we created a P tag. The P tag holds the text and displays the task after the user adds a task.
We created a button tag and adds inner text “x” it and we want when a user clicks the button it should delete a completed task or any task at all.
We added an event listener to fire the button whenever a click event has been made.
The TodoList.splice(i, 1)
deletes a task from the localStorage and after that, we run the function again.
item.appendChild(checkbox);
item.appendChild(text);
item.appendChild(button);
todo.appendChild(item);
input.value = null;
The item.appendChild()
appends all the Html elements that we created to the DOM and also arrenge then orderly just as the image below.
Conclusion
In this article, we were able to build a simple to-do list app that allows users to add new tasks, mark a task as completed, and delete completed tasks. I hope we learned something new.
Have a beautiful day and stay safe!