Make a Todo App with Native JavaScript
Many people share how to make a todo app using JavaScript library like Vue or React. I think by making one with just pure native JavaScript, I can train myself with project structuring.
<div>
<input id ="todoinput">
<button onclick = "add()">Add</button>
</div>
<ol id = "todos"></ol>
<script>
var i = 1;
function add(){
var newtodo = document.createElement('li');
newtodo.setAttribute("id","todo" + i);
newtodo.innerHTML = `${todoinput.value}<button onclick = "deletefunc(${i})">Delete</button><button onclick = "updatefunc(${i})">Update</button>`;
todos.appendChild(newtodo);
todoinput.value = "";
i++;
};
function deletefunc(n){
todos.removeChild(document.getElementById("todo" + n));
}
function updatefunc(n){
document.getElementById("todo" + n).innerHTML = `${todoinput.value}<button onclick = "deletefunc(${n})">Delete</button><button onclick = "updatefunc(${n})">Update</button>`;
todoinput.value = "";
}
</script>
Keypoints
- I use `` to specify todo list item innerHTML and ${} sign to escape into JavaScript code.
- The structure of this app is based on inreasing index "i" that is the unique id of each todo list. With this "i", I can control which todo is to delete or update.
- One can easily integrate the front-end js code to back-end server via fetch request. This frond end app can prevent user from constant refreshing web browser or sending get request every time a to-do is added, updated or deleted in order to update the user interface. This can reduce access to database and reduce money spent on traffic to database.
Comments
Post a Comment